Tuesday 9 June 2015

Send Email Via Gmail with Java Mail API in Android

To Android app that are capable of sending an automatic mail without prompting user for to address, from address, subject and body of mail. In a simple word, we need to create an Android app that sends from address of the user to a particular mail-ID.

For use of this you need to download the some jar file from Here.
1.  additional.jar
2. mail.jar
3. activation.jar

Download these jar file and make a java build path with your project. 

Below is sendEmail() method for sending email. use this method in your application and enjoy :)


public void sendEmail() throws AddressException, MessagingException {
String host = "smtp.gmail.com";
String address = "abc@gmail.com";
String from = "abc@gmail.com";
String pass = "123456789";
String to = "abc@live.com";
Multipart multiPart;
String finalString = "fsdfsdfdsfdsfdsf";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", address);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Log.i("Check", "done pops");
Session session = Session.getDefaultInstance(props, null);
DataHandler handler = new DataHandler(new ByteArrayDataSource(
finalString.getBytes(), "text/plain"));
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setDataHandler(handler);
Log.i("Check", "done sessions");
multiPart = new MimeMultipart();
InternetAddress toAddress;
toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
Log.i("Check", "added recipient");
message.setSubject("Send Auto-Mail");
message.setContent(multiPart);
message.setText("Demo For Sending Mail in Android Automatically \n");
Log.i("check", "transport");
Transport transport = session.getTransport("smtp");
Log.i("check", "connecting");
transport.connect(host, address, pass);
Log.i("check", "wana send");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Log.i("check", "sent");

}