Skip to content

Instantly share code, notes, and snippets.

@spullara
Created September 21, 2010 23:02
Show Gist options
  • Select an option

  • Save spullara/590747 to your computer and use it in GitHub Desktop.

Select an option

Save spullara/590747 to your computer and use it in GitHub Desktop.
public static boolean sendMail(String to, String from, String subject, String text, String host, String port, String user, String password) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtps.host", host);
props.put("mail.smtps.port", port);
props.put("mail.smtps.user", user);
props.put("mail.smtps.password", password);
return sendMail(to, from, subject, text, props);
}
public static boolean sendMail(String to, String from, String subject, String text, Properties props) {
Session mailSession = Session.getDefaultInstance(props);
MimeMessage simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress;
InternetAddress toAddress;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
System.err.println("Failed to send email: " + e);
return false;
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(Message.RecipientType.TO, toAddress);
simpleMessage.setSubject(subject, "UTF-8");
simpleMessage.setText(text, "UTF-8");
Transport tr = mailSession.getTransport(protocol);
tr.connect(props.getProperty("mail.smtps.host"), Integer.parseInt(props.getProperty("mail.smtps.port")), props.getProperty("mail.smtps.user"), props.getProperty("mail.smtps.password"));
simpleMessage.saveChanges();
tr.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
tr.close();
} catch (MessagingException e) {
System.err.println("Failed to send email: " + e);
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment