Scenario:
How to use JavaMail API to send authenticated SMTP Emails?
How to use JavaMail with MX Outbound as the SMTP Provider?
Solution:
The example code below shows how to use the JavaMail API to send emails using MX Outbound as the SMTP Provider for email delivery.
import java.io.*; import java.util.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String[] args) { // SMTP Server Details final String hostServer = "mxoXXXX.mxtools.co.uk"; final String hostPort = "25"; final String hostUsername = "mxo-username"; final String hostPassword = "mxo-password"; // Recipient's Email Address String toEmail = "This email address is being protected from spambots. You need JavaScript enabled to view it."; // Sender's Email Address String fromEmail = "This email address is being protected from spambots. You need JavaScript enabled to view it."; String fromEmailName = "Firstname Lastname"; // Set the email properties Properties props = new Properties(); props.put("mail.smtp.host", hostServer); // SMTP Host props.put("mail.smtp.port", hostPort); // SMTP Port props.put("mail.smtp.auth", "true"); // SMTP Authentication Enabled // If you don't want a TLS session then comment out the below line props.put("mail.smtp.starttls.enable", "true"); // Enable STARTTLS // Create an authenticator object Authenticator auth = new Authenticator() { //override the getPasswordAuthentication method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(hostUsername, hostPassword); } }; // Create the Session Session session = Session.getInstance(props, auth); try { // Create the MIME Message and compose the message MimeMessage msg = new MimeMessage(session); // Set message headers msg.addHeader("Content-type", "text/HTML; charset=UTF-8"); msg.addHeader("Content-Transfer-Encoding", "8bit"); msg.setSentDate(new Date()); // Add the Senders information msg.setFrom(new InternetAddress(fromEmail, fromEmailName)); msg.setReplyTo(InternetAddress.parse(fromEmail, false)); // Add the subject msg.setSubject("Subject of the email goes here", "UTF-8"); // Add the message bosy msg.setText("Body of the message goes here", "UTF-8"); // Add the Recipients msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false)); // Send the message Transport.send(msg); System.out.println("EMail Sent Successfully!!"); } catch (Exception e) { e.printStackTrace(); } } }
Summary of server details
Outgoing server |
As provided. |
Outgoing server protocol |
SMTP |
Outgoing server port |
25, 465, 587, 2525, 8025 or 10025 |
Authentication Type |
Basic Authentication |
Username |
As provided |
Password |
As provided |