Skip to content

Instantly share code, notes, and snippets.

@swapnull-in
Created April 15, 2014 06:56
Show Gist options
  • Save swapnull-in/10708674 to your computer and use it in GitHub Desktop.
Save swapnull-in/10708674 to your computer and use it in GitHub Desktop.
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
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 SendMail {
private String SMTP_HOST = "smtp.gmail.com";
private String FROM_ADDRESS = "[email protected]";
private String PASSWORD = "password";
private String FROM_NAME = "Test Email";
public static void main(String[] args) {
System.out.println("Start .......... ");
SendMail sendMail = new SendMail();
try {
ArrayList<String> recipients = new ArrayList<String>();
recipients.add("[email protected]");
String body = "<ul><li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li><li>Aliquam tincidunt mauris eu risus.</li><li>Vestibulum auctor dapibus neque.</li></ul>";
sendMail.sendMail(recipients, "Some Subject", body);
} catch (Exception e) {
}
}
public boolean sendMail(ArrayList<String> recipients, String subject, String body) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.port", "25");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM_ADDRESS,
PASSWORD);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM_ADDRESS));
// message.setRecipients(Message.RecipientType.TO,
// InternetAddress.parse("[email protected]"));
InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
message.setFrom(from);
InternetAddress[] toAddresses = new InternetAddress[recipients
.size()];
System.out.println("Sending mail to this recipoents as CC");
for (int i = 0; i < recipients.size(); i++) {
System.out.println(recipients.get(i));
toAddresses[i] = new InternetAddress(recipients.get(i));
}
message.setRecipients(Message.RecipientType.TO, toAddresses);
message.setSubject(subject);
message.setContent(body, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Mail Sent");
return true;
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment