Sending e-mail in Java via SMTP protocol

I was attempting to send e-mail, using the following code, in Java but was receiving SMTP protocol errors. I thought perhaps I required authentication or some other type of initilization, but turns out the problem was just missing jars.

Java code:

Properties emailProps = new Properties();
emailProps.setProperty("mail.host", "<YOUR_SMTP_HOST>");
emailProps.setProperty("mail.debug", "true");


Session session = Session.getInstance(emailProps);
Message msg = new MimeMessage(session);


try {
msg.setSubject("<YOUR MESSAGE>");
msg.setSentDate(new Date());
msg.setFrom(InternetAddress.parse("<FROM_ADDRESS>")[0]);
msg.setRecipient(Message.RecipientType.TO,
InternetAddress.parse("<TO_ADDRESS>", false)[0]);
msg.setText(<YOUR_MESSAGE_TEXT>);
Transport.send(msg);
} catch (MessagingException e) {
e.printStackTrace();
}

Exception I was getting:
javax.mail.NoSuchProviderException: Unable to locate provider for protocol: smtp

Solution:
Include the following dependencies (maven2 example):

<dependency>
<groupId>org.apache.geronimo.javamail</groupId>
<artifactId>geronimo-javamail_1.4_mail</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-activation_1.1_spec</artifactId>
<version>1.1</version>
</dependency>

Advertisements

5 thoughts on “Sending e-mail in Java via SMTP protocol

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s