Skip to content

Instantly share code, notes, and snippets.

@hans
Created July 29, 2011 23:00
Show Gist options
  • Save hans/1114931 to your computer and use it in GitHub Desktop.
Save hans/1114931 to your computer and use it in GitHub Desktop.
JavaMail: Sending an email message to an SMTP server which uses authentication
import java.util.Properties;
import javax.mail.Authenticator;
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;
import javax.mail.internet.MimeMessage.RecipientType;
public class SMTPAuthEmail {
private Session session;
public static void main(String[] args) throws MessagingException {
new SMTPAuthEmail().send();
}
public SMTPAuthEmail() {
Authenticator authenticator = new Authenticator() {
private PasswordAuthentication authentication;
{
authentication = new PasswordAuthentication("username", "password");
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
};
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.somewhere.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(props, authenticator);
}
private void send() throws MessagingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Hello world!");
message.setContent("Sent via an SMTP server with authentication.", "text/plain");
Transport.send(message);
}
}
Authenticator authenticator = new Authenticator() {
private PasswordAuthentication authentication;
{
authentication = new PasswordAuthentication("username", "password");
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
};
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.somewhere.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, authenticator);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Hello world!");
message.setContent("Sent via an SMTP server with authentication.", "text/plain");
Transport.send(message);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment