by
226 9
2
5
2,715
3
Top 1% !
Popular
Famous
Specified
OpenSource
Popularity: 5941st place
Created
Modified Feb 4, 2014

Published on:

No tags for this snippet yet.
JVMjre7
LanguageJava
LicenseMIT_X11

Sending multiple email using Java ( Using Gmail SMTP )

Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/26172/Sending-multiple-email-using-Java-(-Usin?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class JavaEmail { Session mailSession; public static void main(String args[]) throws AddressException, MessagingException { JavaEmail javaEmail = new JavaEmail(); javaEmail.setMailServerProperties(); javaEmail.draftEmailMessage(); javaEmail.sendEmail(); } private void setMailServerProperties() { Properties emailProperties = System.getProperties(); emailProperties.put("mail.smtp.port", "587"); emailProperties.put("mail.smtp.auth", "true"); emailProperties.put("mail.smtp.starttls.enable", "true"); mailSession = Session.getDefaultInstance(emailProperties, null); } private MimeMessage draftEmailMessage() throws AddressException, MessagingException { String[] toEmails = { "Google@gmail.com" }; String emailSubject = "Test email subject"; String emailBody = "This is a test message"; MimeMessage emailMessage = new MimeMessage(mailSession); /** * Set the mail recipients * */ for (int i = 0; i < toEmails.length; i++) { emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i])); } emailMessage.setSubject(emailSubject); /** * If sending HTML mail * */ emailMessage.setContent(emailBody, "text/html"); /** * If sending only text mail * */ //emailMessage.setText(emailBody);// for a text email return emailMessage; } private void sendEmail() throws AddressException, MessagingException { /** * Sender's credentials * */ String fromUser = "user-email@gmail.com"; String fromUserEmailPassword = "*******"; String emailHost = "smtp.gmail.com"; Transport transport = mailSession.getTransport("smtp"); transport.connect(emailHost, fromUser, fromUserEmailPassword); /** * Draft the message * */ MimeMessage emailMessage = draftEmailMessage(); /** * Send the mail * */ transport.sendMessage(emailMessage, emailMessage.getAllRecipients()); transport.close(); System.out.println("Email sent successfully."); } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus