Skip to content

Instantly share code, notes, and snippets.

@dodalovic
Last active March 16, 2016 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dodalovic/f578372ba0170785b4ef to your computer and use it in GitHub Desktop.
Save dodalovic/f578372ba0170785b4ef to your computer and use it in GitHub Desktop.
Send mail via Gmail / SMTP using Apache commons mail
package rs.dodalovic.send_mail;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import javax.mail.util.ByteArrayDataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class ApacheCommonsEmailSenderMain {
public static final String HOST_NAME = "smtp.gmail.com";
public static final int PORT = 465;
public static final String TEXT_PLAIN = "text/plain";
public static void main(String[] args) throws IOException, EmailException {
final String userName = args[0];
final String password = args[1];
final String recipientEmailAddress = args[2];
final String attachmentLocation = args[3];
HtmlEmail email = new HtmlEmail();
email.setHostName(HOST_NAME);
email.setSmtpPort(PORT);
email.setSSLOnConnect(true);
email.setAuthentication(userName, password);
email.setSubject("Some subject");
email.setFrom(userName, "Firstname Lastname", String.valueOf(StandardCharsets.UTF_8));
email.addTo(recipientEmailAddress);
email.setHtmlMsg("<h3>Message body</h3>");
ByteArrayDataSource dataSource = new ByteArrayDataSource(new FileInputStream(attachmentLocation), TEXT_PLAIN);
email.attach(dataSource, "attachment", "attachment");
email.send();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment