I want to create app on android and make it config E-mail setting on android device programmatically when it get setting data from server.
I have search around for android code example but I can't find any good example and I don't know where to start looking.
Can any one suggest where should I start looking?
Thank you
Update Sorry for an unclear question.
I used this method to send email programmatically . you can use this. it will help you.
//send email
boolean sendMail(String from,String to)
{
boolean isSend=false;
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true"); //enable for gmail
props.put("mail.smtp.user", "abc#gmail.com");
props.put("mail.smtp.password", "abc");
props.put("mail.smtp.port", "587"); //gmail port address
props.put("mail.smtp.auth", "true");
Log.d("tag","props set");
Session session = Session.getDefaultInstance(props,null);
Log.d("tag","session set");
MimeMessage message = new MimeMessage(session);
Log.d("tag","message set");
try {
message.setFrom(new InternetAddress(from));
InternetAddress add = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, add);
message.setSubject("hello");
message.setText("hello world");
Transport transport = session.getTransport("smtp");
transport.connect(host,from, "hello world");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
isSend=true;
}
catch (AddressException ae) {
ae.printStackTrace();
isSend=false;
}
catch (MessagingException me) {
me.printStackTrace();
isSend=false;
}
return isSend;
}
Related
I am getting a message in raw format . Then got the Mimemessage by
MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));
Now email.getSubject is returning right value but
email.getReceivedDate is null
Please explain this behaviour. Is this the right way to decode different parts of the mail
com.google.api.services.gmail.model.Message fullMessage = mService.users().messages().get(acct.sEmail, message.getId()).setFormat("raw").execute();
Properties props = new Properties();
idg.javax.mail.Session session = idg.javax.mail.Session.getDefaultInstance(props, null);
byte[] emailBytes = com.google.api.client.util.Base64.decodeBase64(fullMessage.getRaw());
try {
idg.javax.mail.internet.MimeMessage email = new idg.javax.mail.internet.MimeMessage(session, new ByteArrayInputStream(emailBytes));
Log.i("Received date","is" + email.getReceivedDate() + message.getId());
Log.i("subject", "is" + email.getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
yes you can use getReceivedDate() for MimeMessage and yes, ofcourse its the better way to retrieve the values for different parts of mail.
This is to retrieve MimeMessage:
Users MimeMessage
This is to get Different Properties of mail :MimeMessage Properties
I need to send an e-mail with attachments automatically without user input. I previously read these 2 answers.
Sending Email in Android using JavaMail API without using the default/built-in app
Android: Send e-mail with attachment automatically in the background.
But now I don't receive any e-mail and I already enabled the less secure apps in gmail. Here's my code :
public class Mail {
private String mailhost;
private String user;
private String password;
private Session session;
private String serverport;
public void main(String user, String password, String subject, String body){
sendFromGMail(user, password, subject,body);
}
private void sendFromGMail(String from, String pass, String subject, String body){
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
MimeMessage message = new MimeMessage(session);
try {
InternetAddress adressTo = new InternetAddress(from);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, adressTo);
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch(MessagingException e){
Log.e("Not Sent", e.getMessage(), e);
}
}
}
And this is how I use it :
try {
Mail mail = new Mail();
mail.main(gmailusername, gmailpassword, "Test", "Test2");
this.publishProgress("Email Sent");
}catch(Exception e){
Log.e("SendMail", e.getMessage(), e);
this.publishProgress("Email not sent");
}
Edit : I don't want to use the built-in app as the title suggested. Just wanted to make it clear.
Java debug :
08-12 15:08:41.152 24062-24340/com.documax.cardreader I/System.out﹕ DEBUG: setDebug: JavaMail version 1.4.1
08-12 15:08:41.162 24062-24340/com.documax.cardreader I/System.out﹕ DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4.1]
08-12 15:08:41.162 24062-24340/com.documax.cardreader I/System.out﹕ DEBUG SMTP: useEhlo true, useAuth true
08-12 15:08:41.162 24062-24340/com.documax.cardreader I/System.out﹕ DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
Fix all these common mistakes, including getting rid of the Authenticator.
Get rid of the call to super() in your constructor, you don't need it.
Also, get rid of the ByteArrayDataSource class. You don't need your own since it comes with JavaMail. Plus, your program isn't even using it.
If it still doesn't work, update your post with your new code and new failure details.
My sendEmail() function works in Eclipse with straight Java and I can send emails without any issue, but once I plug the function into my Android application none of the emails are being sent. I have added the javax.mail and javax.activation JARs to my build path in both cases. Here is the code for the function and then the LogCat reading. On a button click sendEmailCustomer() is called and nothing occurs. Any suggestions are more than appreciated.
public void sendEmailCustomer() {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.stmp.user", "user");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "user";
String password = "password";
return new PasswordAuthentication(username, password);
}
});
EditText e = (EditText) findViewById(R.id.enterEmail);
String to = e.toString();
String from = "user";
String subject = "Testing...";
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(
to));
msg.setSubject(subject);
msg.setText("Did you get this?");
Transport transport = session.getTransport("smtp");
transport.send(msg);
} catch (Exception exc) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(exc.toString());
builder.setTitle("Error!");
builder.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
}
Updated LogCat errors. It sounds like the application cannot access the internet even though it has permission in my manifest. Why is this?
04-03 12:38:07.166: W/IInputConnectionWrapper(2528): showStatusIcon on inactive InputConnection
04-03 12:38:07.166: W/IInputConnectionWrapper(2528): InputConnection =
com.android.internal.widget.EditableInputConnection#411c5f28, active client = false
You'll want to fix these common mistakes, and this mistake. You might just want to copy this code for connecting to Gmail. If that still doesn't work for you, follow these debugging steps to get more information so we can help you.
Note also that you can use the latest JavaMail jar file instead of the older mail.jar file linked to above.
Make sure you're referencing your JAR libraries in your project and at the same time, use the Android version of JavaMail too.
try to add this lines in your "AndroidManifest.xml" file
<manifest... >
....
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
....
</manifest>
maybe your problem is with the internet permission.
Please refer to this SO thread for the solution. I also reccomend checking the permissions in your AndroidManifest.xml like SUNDAY suggested.
Hello Friends i wan to make editable false in all edittext when i send mail by my application
programmatically
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto","test#mymail.com, null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "My Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Message);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
finish();
friends my question is i want Text Subject Feild and Text/Body feild Read Only user can not edited it's value so how can i make it any idae?
your passing a intent to android device to handle mailing function specifying to handle it once intent is passed it will be handle by gmail or any other email client installed in your phone once they handle and get your data that is subject and message your application will be in paused state i mean to say you don't have control over other applications that handles your data.
create your mail handling and sending mail instead of passing it as intent
set editable false works only when you have those edit fields inside your application not in other activities that are started by your intent
You can create you own email sending activity without passing intent to any native email client app.There you can easily disable the editText for message and subject. The code for sending email is:
public class SendMail{
public static void main(String[] args) {
final String username = "username#gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email#gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
taken from here
Basically if you choose email chooser of android to send an email you lost all the control over this intent. So overriding these behaviour is very hard and might be not possible. So overcoming on this issue you can follow this link Sending Email in Android using JavaMail API without using the default/built-in app.
You can find how to use the javamail Api as in the above link.
Now you can make your own layout for mail activity. And you can use
youreditetxtWhichyouwanttodisable.setEditable(false);
This might be useful.
I have been trying to write an app that periodically parses the contents of gmail messages. I have been through the JavaMail FAQ and I have looked at a number of examples in the JavaMail download package but have been unable to get this to work. The code below currently causes the following gmail error:
Host is unresolved: imaps.gmail.com:993
I have also tried imap.gmail.com:143 but get:
Host is unresolved: imap.gmail.com:143
Any help or advice would be greatly appreciated. GMailReader is the class I am using to try and return gmail imap messages:
public class GMailReader extends javax.mail.Authenticator {
private String mailhost = "imaps.gmail.com";
private String user;
private String password;
private Session session;
public GMailReader(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "imaps");
props.setProperty("mail.imaps.host", mailhost);
props.put("mail.imaps.auth", "true");
props.put("mail.imaps.port", "993");
props.put("mail.imaps.socketFactory.port", "993");
props.put("mail.imaps.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
public synchronized Message[] readMail() throws Exception {
try {
Store store = session.getStore("imaps");
store.connect("imaps.gmail.com", user, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message[] msgs = folder.getMessages(1, 10);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
return msgs;
} catch (Exception e) {
Log.e("readMail", e.getMessage(), e);
return null;
}
}
}
I found an example here that was helpful. My error was the use of "mail.transport.protocol" rather than "mail.store.protocol."
hereafter a corrected version of
public class GMailReader extends javax.mail.Authenticator {
private static final String TAG = "GMailReader";
private String mailhost = "imap.gmail.com";
private Session session;
private Store store;
public GMailReader(String user, String password) {
Properties props = System.getProperties();
if (props == null){
Log.e(TAG, "Properties are null !!");
}else{
props.setProperty("mail.store.protocol", "imaps");
Log.d(TAG, "Transport: "+props.getProperty("mail.transport.protocol"));
Log.d(TAG, "Store: "+props.getProperty("mail.store.protocol"));
Log.d(TAG, "Host: "+props.getProperty("mail.imap.host"));
Log.d(TAG, "Authentication: "+props.getProperty("mail.imap.auth"));
Log.d(TAG, "Port: "+props.getProperty("mail.imap.port"));
}
try {
session = Session.getDefaultInstance(props, null);
store = session.getStore("imaps");
store.connect(mailhost, user, password);
Log.i(TAG, "Store: "+store.toString());
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized Message[] readMail() throws Exception {
try {
Folder folder = store.getFolder("Inbox");
folder.open(Folder.READ_ONLY);
/* TODO to rework
Message[] msgs = folder.getMessages(1, 10);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
*/
Message[] msgs = folder.getMessages();
return msgs;
} catch (Exception e) {
Log.e("readMail", e.getMessage(), e);
return null;
}
}
}
Bye
I see that the GmailReader concept very usefull and well designed in accordance whith the GmailSender example showed here:
Sending Email in Android using JavaMail API without using the default/built-in app
But Any news, on the error asked below ? And implementation of the proposition of JackN ?
Best Regards
SkN
After a huge amount of trial, error and googling , snakeman's edition of this answer provided the workable example I needed for a gmail reader;
However others should be aware (if using later versions of the Android SDK) of Manifest permission requirements and the need to use asyncTask to move potentially long-running tasks out of the main UI thread), both of which are mentioned in this SMTP example
I should also mention that if, like me, you intend to also implement an smtp sending class, I have seen somewhere a discussion suggesting that session.getInstance should be used in place of session.getDefaultInstance.