Java SMTP Integration Guide

Minimum code that you need to integrate Mailazy with your Java application


Prerequisites

You need to complete these given prerequisites, you can skip the step if you have already completed.

  1. Sign up for a Mailazy account.
  2. Complete Domain Authentication.
  3. Generate the Mailazy Access Key

Integrate Mailazy with Java

Start Sending mail using the code provided below:

import java.util.*;
import java.lang.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;

class Main {
    public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.setProperty("mail.smtp.host", "smtp.mailazy.com");
        properties.setProperty("mail.smtp.port", "587"); //TLS Port
        properties.setProperty("mail.smtp.auth", "true"); //enable authentication
        properties.setProperty("mail.smtp.starttls.enable", "true");

        //create Authenticator object to pass in Session.getInstance argument
        Authenticator auth = new Authenticator() {
            //override the getPasswordAuthentication method
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("ACCESS_KEY", "ACCESS_SECRET");
            }
        };
        Session session = Session.getInstance(properties, auth);

        final Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("[email protected]", "sender"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
        msg.setSubject("Hello world!");
        // Unformatted text version
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent("Hello Bob!", "text/plain; charset=utf-8");
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent("Hello <b>Bob</b>!", "text/html; charset=utf-8");
        // Create the Multipart. Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");

        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);

        // Set Multipart as the message's content
        msg.setContent(mp);

        // Send
        Transport.send(msg);
    }
}