Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Authenticate With SMTP Server Before Sending Email

DZone's Guide to

Authenticate With SMTP Server Before Sending Email

Free Resource

Today’s data climate is fast-paced and it’s not slowing down. Here’s why your current integration solution is not enough. Brought to you in partnership with Liaison Technologies.

For more info see: http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html

You need activation.jar, smtp.jar, and mailapi.jar in your classpath for this to work.


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;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailWithPasswordAuthentication {
public static void main(String[] args) throws MessagingException {
new MailWithPasswordAuthentication().run();
}

private void run() throws MessagingException {
Message message = new MimeMessage(getSession());

message.addRecipient(RecipientType.TO, new InternetAddress("to@example.com"));
message.addFrom(new InternetAddress[] { new InternetAddress("from@example.com") });

message.setSubject("the subject");
message.setContent("the body", "text/plain");

Transport.send(message);
}

private Session getSession() {
Authenticator authenticator = new Authenticator();

Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");

properties.setProperty("mail.smtp.host", "mail.example.com");
properties.setProperty("mail.smtp.port", "25");

return Session.getInstance(properties, authenticator);
}

private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;

public Authenticator() {
String username = "auth-user";
String password = "auth-password";
authentication = new PasswordAuthentication(username, password);
}

protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
}



Is iPaaS solving the right problems? Not knowing the fundamental difference between iPaaS and iPaaS+ could cost you down the road. Brought to you in partnership with Liaison Technologies.

Topics:
authentication

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}