Programatically Sending emails From Gmail Using Java
There might be a scenario where you would want to send email’s using gmail programatically. The following example shows how its done programatically using Java. The email content is sent in the html format, which comes in pretty handy. The recipient email doesn’t necessarily have to be a gmail, it can be any valid email from any email provider. Make sure you have javax.mail jar on your classpath.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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; public class Gmail{ public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); 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 javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("YOUR_MAILID@gmail.com", "YOUR_GMAIL_PASSWORD"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("YOUR_MAILID@gmail.com")); //to send to multiple recipients, have them comma separated message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("TO_RECIPIENT_MAIL_IDS_COMMA_SEPARATED")); message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("CC_RECIPIENT_MAIL_IDS_COMMA_SEPARATED")); message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse("BCC_RECIPIENT_MAIL_IDS_COMMA_SEPARATED")); message.setSubject("YOUR_SUBJECT"); StringBuilder sb = new StringBuilder(); sb.append("<!DOCTYPE html>"); sb.append("<html lang='en'>"); sb.append("<head>"); sb.append(" <meta charset='UTF-8'>"); sb.append(" <title>Sample Email</title>"); sb.append("</head>"); sb.append("<body>"); sb.append(" <b>This should be in bold</b>"); sb.append(" <i>In italics as well</i>"); sb.append("</body>"); sb.append("</html>"); message.setContent(sb.toString(), "text/html; charset=utf-8"); Transport.send(message); System.out.println("Mail Sent"); } catch (MessagingException e) { throw new RuntimeException(e); } } } |
“A little programming knowledge goes a long way.”
-Rushi
-Rushi