Skip to content

Instantly share code, notes, and snippets.

@seunggabi
Last active November 9, 2019 14:17
Show Gist options
  • Save seunggabi/c902e76c0465666ea699dbefa065965c to your computer and use it in GitHub Desktop.
Save seunggabi/c902e76c0465666ea699dbefa065965c to your computer and use it in GitHub Desktop.
sendEmail.java
public static void sendEmail(String emailString, String subject, String message, File file) {
String[] emails = StringUtils.split(emailString, ",");
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "localhost");
Session session = Session.getDefaultInstance(props);
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress("from@localhost", "from"));
for (String email : emails) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "user"));
}
msg.addRecipient(Message.RecipientType.CC, new InternetAddress("admin@localhost", "cc"));
msg.setSubject(subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/plain; charset=UTF-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
if(file != null) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(FILENAME);
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment