I just finished with sending Email using Java Mail by connecting the Gmail SMTP.
Please ensure the Gmail account is NOT using Gmail 2 Step Verification, and allow less secure apps to have access,
Because Java Mail works here as a Less secure App.
You can do it using following Link
https://www.google.com/settings/security/lesssecureapps
Askerali Maruthullathil
package org.core.mail;
import java.util.Properties;
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;
import javax.mail.internet.AddressException;
public class SendEmailUsingGMailSMTP {
public static void main(String[] args) throws AddressException, MessagingException {
Properties mailServerProperties;
Session getMailSession;
MimeMessage generateMailMessage;
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "465");
mailServerProperties.put("mail.smtp.socketFactory.port", "465");
mailServerProperties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
mailServerProperties.put("mail.smtp.auth", "true");
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");
getMailSession = Session.getDefaultInstance(mailServerProperties, null);
generateMailMessage = new MimeMessage(getMailSession);
generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("to@gmail.com"));
generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("cc@gmail.com"));
generateMailMessage.setSubject("Test Mail from Java Mail");
String emailBody = "Test email by Java Mail JavaMail API example. " + "\n Regards, \nAdmin";
generateMailMessage.setContent(emailBody, "text/html");
System.out.println("Mail Session has been created successfully..");
Transport transport = getMailSession.getTransport("smtp");
transport.connect("smtp.gmail.com", "mail@gmail.com", "password");
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
transport.close();
}
}
Please ensure the Gmail account is NOT using Gmail 2 Step Verification, and allow less secure apps to have access,
Because Java Mail works here as a Less secure App.
You can do it using following Link
https://www.google.com/settings/security/lesssecureapps
If we want to sent the HTML content Email with an attachment, try the following
package org.core.mail;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public class SendEmailUsingGMailSMTP {
public static void main(String[] args) throws AddressException, MessagingException, IOException {
String emailAddress = "fromemail@gmail.com";
String emailBody = "Test email by Java Mail using JavaMail API example. "
+ "\n Regards, \n Asker";
//call readFile to read the HTML template file and send it through email, and attach the the image from the resourse we have.
//emailBody = readFile()
sendEmail(emailAddress, emailBody);
}
public static void sendEmail(String emailAddress, String emailBody) throws AddressException, MessagingException, IOException {
// Step1
System.out.println("\n 1st ===> setup Mail Server Properties..");
Properties mailServerProperties;
Session mailSession;
MimeMessage mailMessage;
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "465");
mailServerProperties.put("mail.smtp.socketFactory.port", "465");
mailServerProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
mailServerProperties.put("mail.smtp.auth", "true");
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");
// Step2
System.out.println("\n\n 2nd ===> get Mail Session..");
mailSession = Session.getDefaultInstance(mailServerProperties, null);
mailMessage = new MimeMessage(mailSession);
mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
mailMessage.setSubject("Greetings from Asker..");
System.out.println("Mail Session has been created successfully..");
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setHeader("Content-Type", "text/html");
DataSource dataSourceHtml= new ByteArrayDataSource(emailBody, "text/html");
messageBodyPart1.setDataHandler(new DataHandler(dataSourceHtml));
// 4) create new MimeBodyPart object and set DataHandler object to
// this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
URL url=SendEmailUsingGMailSMTP.class.getResource("lesssecure.jpg");
DataSource source = new FileDataSource(url.getFile());
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName("My Image.jpg");
// 5) create Multipart object and add MimeBodyPart objects to this
// object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
mailMessage.setContent(multipart);
// Step3
System.out.println("\n\n 3rd ===> Get Session and Send mail");
Transport transport = mailSession.getTransport("smtp");
// Enter your correct gmail UserID and Password
// if you have 2FA enabled then provide App Specific Password
transport.connect("smtp.gmail.com", "email@gmail.com", "password");
transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
transport.close();
}
private static String readFile( ) throws IOException, URISyntaxException {
BufferedReader reader = new BufferedReader( new FileReader (new File(SendEmail.class.getResource("template.html").toURI())));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
try {
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
}
Askerali Maruthullathil


