What should I do if an error occurs when sending javaMail (Le bytes)

Posted May 30, 202011 min read

Java Mail to send mail

Detailed how Spring sends mail

This article is exclusively sponsored by Lebyte Java Architecture Course

Send plain text messages

package com.xxxx.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail. *;
import javax.mail.internet. *;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
* Send regular text emails
* /
public class MailTest01 {

    public static void main(String []args) throws Exception {

        //Define mailbox server configuration
        Properties prop = new Properties();
        //Set mail server host name(163 mail server address:"mail.smtp.host" "smtp.163.com")
        prop.setProperty("mail.smtp.host", "smtp.163.com");
        //Set the port of the mail server
        prop.setProperty("mail.smtp.port", "25");
        //Set the authentication attribute of the mail server(setting to true means that the sending server requires authentication)
        prop.setProperty("mail.smtp.auth", "true");
        //Some mailbox servers require SSL security authentication for SMTP connections
        //prop.setProperty("mail.smtp.port", "465");
        //prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        //prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        //prop.setProperty("mail.smtp.socketFactory.port", "465");

        //5 steps to send mail using JavaMail
        //1. Create a session
        Session session = Session.getInstance(prop);
        //Open the debug mode of Session, so that you can check the running status of the program sending Email
        session.setDebug(true);
        //2. Get the transport object through session
        Transport ts = session.getTransport();
        //3. Use the user name and password of the mailbox to connect to the mail server(the user name only needs to write @front, the password refers to the authorization code)
        ts.connect("smtp.163.com", "Username", "Password");
        //4. Create mail
        //Send normal text email
        Message message = createSimpleTxtMail(session);

        //5. Send mail
        ts.sendMessage(message, message.getAllRecipients());
        //Close the transport object
        ts.close();

    }

   /**
     * Regular text mail
     * Create a message containing only text
     * @param session
     * @return
     * /
    public static MimeMessage createSimpleTxtMail(Session session) throws MessagingException {
        //Create mail object
        MimeMessage message = new MimeMessage(session);
        //Set the email address of the sender of the email
        message.setFrom(new InternetAddress("Sender's email address"));
        //Set the email address of the recipient of the message(now the sender and the recipient are the same, that is, send it to yourself)
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient's email address"));

        //Send to multiple recipients
        //message.setRecipients(Message.RecipientType.TO, new InternetAddress []{});
        //Cc:Cc(optional)
        //message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(""));
        //Bcc:Bcc(optional)
        //message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(""));

        //Subject of the message
        message.setSubject("Test Text Mail");
        //Set the sending date
        message.setSentDate(new Date());
        //The text content of the email(setText():plain text content)
        message.setText("Hello, this is a test email!");

        //Return the created mail object
        return message;
    }
}

The effect is as follows:

! \ []()

Send emails with HTML content

package com.xxxx.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

/**
* Send emails with HTML content
* /
public class MailTest02 {

    public static void main(String []args) throws Exception {

        //Define mailbox server configuration
        Properties prop = new Properties();
        //Set mail server host name(163 mail server address:"mail.smtp.host" "smtp.163.com")
        prop.setProperty("mail.smtp.host", "smtp.163.com");
        //Set the port of the mail server
        prop.setProperty("mail.smtp.port", "25");
        //Set the authentication attribute of the mail server(setting to true means that the sending server requires authentication)
        prop.setProperty("mail.smtp.auth", "true");

        //5 steps to send mail using JavaMail
        //1. Create a session
        Session session = Session.getInstance(prop);
        //Open the debug mode of Session, so that you can check the running status of the program sending Email
        session.setDebug(true);
        //2. Get the transport object through session
        Transport ts = session.getTransport();
        //3. Use the user name and password of the mailbox to connect to the mail server(the user name only needs to write @ in front, the password refers to the authorization code)
        ts.connect("smtp.163.com", "Username", "Password");
        //4. Create mail
        //Send email with HTML content
        Message message = createHtmlMail(session);

        //5. Send mail
        ts.sendMessage(message, message.getAllRecipients());
        //Close the transport object
        ts.close();

    }

   /**
     * HTML content mail
     * Create an email with html content
     * /
    public static MimeMessage createHtmlMail(Session session) throws Exception {

        //Create mail object
        MimeMessage message = new MimeMessage(session);
        //Set the email address of the sender of the email
        message.setFrom(new InternetAddress("Sender's email address"));
        //Set the email address of the recipient of the message(now the sender and the recipient are the same, that is, send it to yourself)
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient's email address"));
        //Subject of the message
        message.setSubject("Test HTML Mail");
        //Set the sending date
        message.setSentDate(new Date());

        //Prepare email data
       /**
         * Message represents a message, and messgaes.getContent() returns a Multipart object.
         * A Multipart object contains one or more BodyPart objects to form the body part of the message(including attachments).
         * /
        //Create multimedia objects
        MimeMultipart multipart = new MimeMultipart();

        //Create mail body object
        MimeBodyPart bodyPart = new MimeBodyPart();
        //Set HTML content
        StringBuffer sb = new StringBuffer();
        sb.append("<html> <body> <a href='http://www.baidu.com'> Baidu </a> </body> </html>");
        bodyPart.setContent(sb.toString(), "text/html; charset = UTF-8");

        //Set the bodyPart object to the multipart object
        multipart.addBodyPart(bodyPart);
        //Set the multipart object to the message object(setContent() :)
        message.setContent(multipart);

        //Return the created mail object
        return message;
    }
}

The effect is as follows:

! \ []()

Send an email with an attachment

package com.xxxx.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

/**
* Send emails with attachments
* /
public class MailTest03 {

    public static void main(String []args) throws Exception {

        //Define mailbox server configuration
        Properties prop = new Properties();
        //Set mail server host name(163 mail server address:"mail.smtp.host" "smtp.163.com")
        prop.setProperty("mail.smtp.host", "smtp.163.com");
        //Set the port of the mail server
        prop.setProperty("mail.smtp.port", "25");
        //Set the authentication attribute of the mail server(setting to true means that the sending server requires authentication)
        prop.setProperty("mail.smtp.auth", "true");

        //5 steps to send mail using JavaMail
        //1. Create a session
        Session session = Session.getInstance(prop);
        //Open the debug mode of Session, so that you can check the running status of the program sending Email
        session.setDebug(true);
        //2. Get the transport object through session
        Transport ts = session.getTransport();
        //3. Use the user name and password of the mailbox to connect to the mail server(the user name only needs to write @front, the password refers to the authorization code)
        ts.connect("smtp.163.com", "Username", "Password");
        //4. Create mail
        //Send email with attachment
        Message message = createAttachMail(session);

        //5. Send mail
        ts.sendMessage(message, message.getAllRecipients());
        //Close the transport object
        ts.close();

    }

   /**
     * Mail with attachments
     * Create an email with attachments
     * @param session
     * @return
     * @throws MessagingException
     * /
    public static MimeMessage createAttachMail(Session session) throws MessagingException {
        //Create mail object
        MimeMessage message = new MimeMessage(session);
        //Set the email address of the sender of the email
        message.setFrom(new InternetAddress("Sender's email address"));
        //Set the email address of the recipient of the message(now the sender and the recipient are the same, that is, send it to yourself)
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("recipient's email address"));
        //Subject of the message
        message.setSubject("Test mail with attachments");
        //Set the sending date
        message.setSentDate(new Date());


        //Create message body
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent("Mail with attachment created using JavaMail", "text/html; charset = UTF-8");

        //Create attachment
        MimeBodyPart attachPart = new MimeBodyPart();
        //local files
        DataHandler dh = new DataHandler(new FileDataSource("C:\\ work \\ mail attachment.txt"));
        attachPart.setDataHandler(dh);
        //attachment name
        attachPart.setFileName(dh.getName());

        //Create a container to describe the data relationship
        MimeMultipart multipart = new MimeMultipart();
        //Add text
        multipart.addBodyPart(bodyPart);
        //Add attachments
        multipart.addBodyPart(attachPart);
        //If you want to add attachments in the mail, set to mixed ;.
        multipart.setSubType("mixed");

        //Set the content of the email
        message.setContent(multipart);

        //Return the created mail object
        return message;
    }
}

The effect is as follows:

! \ []()

Java Mail mail sending package

Create an email message

package com.xxxx.mail;

import java.util.List;

/**
* Mail sending information
* Define mail server port, sender user name, password and other fields when sending mail
* /
public class MailSendInfo {

    private String serverHost; //server host
    private String serverPort; //server port

    private String fromAddress; //Sender email address
    private List <String> toAddress; //receiver email address

    private String userName; //mail server username
    private String userPwd; //Mail server password(authorization password)

    private String subject; //mail subject
    private String content; //email content

    private Boolean flag = true; //whether identity authentication is required

    private List <String> attachFileNames; //attachment file name


    public Boolean getFlag() {
        return flag;
    }
    public void setFlag(Boolean flag) {
        this.flag = flag;
    }
    public String getServerHost() {
        return serverHost;
    }
    public void setServerHost(String serverHost) {
        this.serverHost = serverHost;
    }
    public String getServerPort() {
        return serverPort;
    }
    public void setServerPort(String serverPort) {
        this.serverPort = serverPort;
    }
    public String getFromAddress() {
        return fromAddress;
    }
    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }
    public List <String> getToAddress() {
        return toAddress;
    }
    public void setToAddress(List <String> toAddress) {
        this.toAddress = toAddress;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPwd() {
        return userPwd;
    }
    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public List <String> getAttachFileNames() {
        return attachFileNames;
    }
    public void setAttachFileNames(List <String> attachFileNames) {
        this.attachFileNames = attachFileNames;
    }
}

Create an authentication class

package com.xxxx.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
* Certification
* /
public class MyAuthenticator extends Authenticator {

    private String userName; //mailbox
    private String userPwd; //password(authorization code)
    public MyAuthenticator(String userName, String userPwd) {
        this.userName = userName;
        this.userPwd = userPwd;
    }

   /**
     * When the mail server sends an email, it performs authentication
     * @return
     * /
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, userPwd);
    }
}

Create an email sender

package com.xxxx.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail. *;
import javax.mail.internet. *;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class MailSender {

    public void sendMail(MailSendInfo mailSendInfo) {
        Message message = null;
        Session session = null;
        try {
            //Define mailbox server configuration
            Properties props = new Properties();
            //163 mail server address
            props.put("mail.smtp.host", mailSendInfo.getServerHost());
            //163 mail server port
            props.put("mail.smtp.port", mailSendInfo.getServerPort());
            //163 mail server authentication attributes
            props.put("mail.smtp.auth", mailSendInfo.getFlag());
            //Identity authentication
            MyAuthenticator authenticator = new MyAuthenticator(mailSendInfo.getUserName(), mailSendInfo.getUserPwd());
            //Create session
            session = Session.getDefaultInstance(props, authenticator);
            //Open the debug mode of Session, so that you can check the running status of the program sending Email
            session.setDebug(true);
            //Create a message object
            message = new MimeMessage(session);
            //Set the email address of the sender
            Address from = new InternetAddress(mailSendInfo.getFromAddress());
            message.setFrom(from);
            //Set the sending time
            message.setSentDate(new Date());

            //determine the recipient's email address
            if(null! = mailSendInfo.getToAddress() && mailSendInfo.getToAddress(). size()> 0) {
                //define the array
                Address []addresses = new Address [mailSendInfo.getToAddress(). Size()];
                //Cyclically obtain the recipient's email address and set it to the corresponding address array
                for(int i = 0; i <mailSendInfo.getToAddress(). size(); i ++) {
                    Address address = new InternetAddress(mailSendInfo.getToAddress(). Get(i));
                    addresses [i]= address;
                }
                //Set the recipient's email address
                message.setRecipients(Message.RecipientType.TO, addresses);
                //set mail subject
                message.setSubject(mailSendInfo.getSubject());

                //Create a multimedia object container
                Multipart multipart = new MimeMultipart();

                //Create text content
                BodyPart bodyPart = new MimeBodyPart();
                bodyPart.setContent(mailSendInfo.getContent(), "text/html; charset = utf-8");
                //Add text(set the content to the multimedia object container)
                multipart.addBodyPart(bodyPart);

                //Get all attachment content
                List <String> files = mailSendInfo.getAttachFileNames();
                //Determine whether to include attachment content
                if(null! = files && files.size()> 0) {
                    for(int i = 0; i <files.size(); i ++) {
                        //Get the corresponding attachment object
                        File tempFile = new File(files.get(i));
                        //Determine whether the attachment exists
                        if(tempFile.exists()) {
                            //If the attachment exists, create an attachment object
                            BodyPart attachPart = new MimeBodyPart();
                            attachPart.setDataHandler(new DataHandler(new FileDataSource(tempFile)));
                            //Set the file name(solve the garbled name of the attachment)
                            attachPart.setFileName(MimeUtility.encodeText(tempFile.getName()));
                            //Add attachment(add attachment content to the multimedia object container)
                            multipart.addBodyPart(attachPart);
                        }
                    }
                }

                //Set email content
                message.setContent(multipart);
                //send email
                Transport.send(message);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Email sending test

Send HTML content email

/**
* Send emails with HTML content
* /
public static void testHtmlMail() {
MailSendInfo mailSendInfo = new MailSendInfo();
mailSendInfo.setServerHost("smtp.163.com");
mailSendInfo.setServerPort("25");
mailSendInfo.setUserName("Mailbox Username");
mailSendInfo.setUserPwd("Password(Authorization Code)");
mailSendInfo.setSubject("Mail Encapsulation");
mailSendInfo.setFromAddress("Sender's Email Address");
mailSendInfo.setContent("

This is the mail sent after encapsulation

");
List users = new ArrayList <>();
users.add("Recipient's email address");
mailSendInfo.setToAddress(users);
MailSender mailSender = new MailSender();
mailSender.sendMail(mailSendInfo);
}

The effect is as follows:

! \ []()

Send an email with an attachment

/**
* Send emails with attachments
* /
public static void testAttachMail() {
MailSendInfo mailSendInfo = new MailSendInfo();
mailSendInfo.setServerHost("smtp.163.com");
mailSendInfo.setServerPort("25");
mailSendInfo.setUserName("User Name");
mailSendInfo.setUserPwd("Password(Authorization Code)");
mailSendInfo.setSubject("Mail Encapsulation");
mailSendInfo.setFromAddress("Sender's Email Address");
mailSendInfo.setContent("

Mail with attachments

");
List users = new ArrayList <>();
users.add("Recipient's email address");
mailSendInfo.setToAddress(users);

    //Add attachments
    List <String> files = new ArrayList <String>();
    files.add("C:\\ work \\ mail attachment.txt");
    files.add("C:\\ work \\ List.xlsx");
    mailSendInfo.setAttachFileNames(files);
    MailSender mailSender = new MailSender();
    mailSender.sendMail(mailSendInfo);
}

The effect is as follows:

! \ []()