Java + Gmail SMTP: Send Email Text, HTML and Attachment Example
February 26, 2015
This page will provide complete tutorial to send email using java and Gmail SMTP. In our example, we will send text, html and attachment in email for the demo. Java provides JavaMail API which uses mail and activation jar. To send email a session is created. Using this session instance we create MimeMessage and finally using Transport.send() method, we send email. To send html content and attachment , JavaMail APi provides MimeMultipart and MimeBodyPart classes. In this tutorial we will learn to send email with
1. Simple text
2. Text and attachment
3. Html content and attachment
To run the program in local machine, we need to make our Gmail account less secure using below steps.
1. Login to Gmail.
2. Access the URL as https://www.google.com/settings/security/lesssecureapps
3. Select "Turn on"
Session and Authenticator
javax.mail.Session is a mail session. Session can be shared and unshared. Default session can be shared by multiple desktop applications. It keeps default values for the mail property. The default properties of session can be overridden asProperties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your_mail_1@gmail.com", "password"); } });
MimeMessage and Transport.send()
javax.mail.internet.MimeMessage represents MIME style email message. MimeMessage implements Message abstract class and MimePart interface. Using MimeMessage class, we set TO, FROM, SUBJECT etc to send mail as below.MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("your_mail_1@gmail.com")); msg.setRecipients(Message.RecipientType.TO, "your_mail_2@gmail.com");
Transport.send(msg);
MimeMultipart and MimeBodyPart
In the case, if we are intended to send HTML content and attachment or both, we need to use javax.mail.internet.MimeMultipart and javax.mail.internet.MimeBodyPart classes. We create an empty MimeMultipart object which has content type as "multipart/mixed". MimeBodyPart represents MIME body part. It implements BodyPart abstract class and MimePart interface. We use these classes asMultipart multipart = new MimeMultipart(); MimeBodyPart attachementPart = new MimeBodyPart(); attachementPart.attachFile(new File("D:/cp/pic.jpg")); multipart.addBodyPart(attachementPart);
MimeMessage.setContent(multipart);
Gradle File for Mail and Activation JAR
Find the Gradle file to resolve the mail and activation jar.build.gradle
apply plugin: 'java' apply plugin: 'eclipse' archivesBaseName = 'Concretepage' version = '1.0-SNAPSHOT' repositories { maven { url "https://repo.spring.io/libs-release" } mavenLocal() mavenCentral() } dependencies { compile 'javax.mail:mail:1.4.7' compile 'jaf:activation:1.0.2' }
Send Email with Simple Text
In this example we send a simple text to recipient using Gmail SMTP.SendSimpleMail.java
package com.concretepage; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendSimpleMail { public static void main(String[] args) { 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"); props.put("mail.debug", "true"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your_mail_1@gmail.com", "password"); } }); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("your_mail_1@gmail.com")); msg.setRecipients(Message.RecipientType.TO, "your_mail_2@gmail.com"); msg.setSubject("Simple Test Mail"); msg.setSentDate(new Date()); msg.setText("Hello World!"); Transport.send(msg); System.out.println("---Done---"); } catch (MessagingException mex) { mex.printStackTrace(); } } }
Subject: Simple Test Mail MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Hello World! . 250 2.0.0 OK 1424959435 c17sm1093738pdl.79 - gsmtp QUIT 221 2.0.0 closing connection c17sm1093738pdl.79 - gsmtp ---Done---
Send Email with Text and Attachment
Here we will use Multipart and create two MimeBodyPart , one for text and second for attachment.AttachmentWithText.java
package com.concretepage; import java.io.File; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class AttachmentWithText { public static void main(String[] args) { 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"); props.put("mail.debug", "true"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your_mail_1@gmail.com", "password"); } }); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("your_mail_1@gmail.com")); msg.setRecipients(Message.RecipientType.TO, "your_mail_2@gmail.com"); msg.setSubject("Text Mail with Attachment."); msg.setSentDate(new Date()); Multipart multipart = new MimeMultipart(); MimeBodyPart textPart = new MimeBodyPart(); String textContent = "Please find the Attachment."; textPart.setText(textContent); multipart.addBodyPart(textPart); MimeBodyPart attachementPart = new MimeBodyPart(); attachementPart.attachFile(new File("D:/cp/pic.jpg")); multipart.addBodyPart(attachementPart); msg.setContent(multipart); Transport.send(msg); System.out.println("---Done---"); } catch (Exception ex) { ex.printStackTrace(); } } }
------=_Part_0_1361188139.1424959525240-- . 250 2.0.0 OK 1424959535 mi9sm1225699pab.3 - gsmtp QUIT 221 2.0.0 closing connection mi9sm1225699pab.3 - gsmtp ---Done---
Send Email with Html Content and Attachment
This example is almost same as above. Here we have tried to show how to use HTML content and attachment. Create Multipart and create two MimeBodyPart , one for html content and second for attachment.AttachementWithHtmlContent.java
package com.concretepage; import java.io.File; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class AttachementWithHtmlContent { public static void main(String[] args) { 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"); props.put("mail.debug", "true"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your_mail_1@gmail.com", "password"); } }); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("your_mail_1@gmail.com")); msg.setRecipients(Message.RecipientType.TO, "your_mail_2@gmail.com"); msg.setSubject("Html Test Mail with Attachement"); msg.setSentDate(new Date()); Multipart multipart = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); String htmlContent = "<html><body><h1>Html Content</h1></body></html>"; htmlPart.setContent(htmlContent, "text/html"); multipart.addBodyPart(htmlPart); MimeBodyPart attachementPart = new MimeBodyPart(); attachementPart.attachFile(new File("D:/cp/pic.jpg")); multipart.addBodyPart(attachementPart); msg.setContent(multipart); Transport.send(msg); System.out.println("---Done---"); } catch (Exception ex) { ex.printStackTrace(); } } }
------=_Part_0_1361188139.1424959832984-- . 250 2.0.0 OK 1424959843 kg2sm1118833pbc.72 - gsmtp QUIT 221 2.0.0 closing connection kg2sm1118833pbc.72 - gsmtp ---Done---