Java code example for SMTP mail delivery

更新时间:
复制 MD 格式

You can use this Java code example to send emails from Alibaba Mail over SMTP.

Alibaba Mail configuration

SMTP server address: smtp.mxhichina.com or smtp.qiye.aliyun.com

Port: 25 for unencrypted connections, or 465 for SSL-encrypted connections.

//Add a reference to javax.mail in the pom.xml file, or import the javax.mail JAR package into your project.
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

public class EnterpriseMailSend {
    public static void main(String[] args) {
        try{
            //Set the SSL connection and mail environment.
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties props = System.getProperties();
            //Protocol
            //props.setProperty("mail.transport.protocol", "smtp");

            props.setProperty("mail.smtp.host", "smtp.mxhichina.com");//SMTP server address
            //props.setProperty("mail.smtp.port", "25");//Unencrypted port
            // To use SSL encryption, apply the following configuration:
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.setProperty("mail.smtp.ssl.enable", "true");
            //props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");//If the default version fails, try specifying a version.

            props.setProperty("mail.smtp.auth", "true");//Specifies that identity authentication is required to send emails over SMTP.
            props.setProperty("mail.smtp.from", "sender_address");//The mailfrom parameter.
            props.setProperty("mail.user","sender_address");//The sender's account.
            props.setProperty("mail.password","sender_password");//The password for the sender's account. If you enabled a security password for third-party clients, use the newly generated password.
            //Create a mail session.
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                //Identity authentication.
                protected PasswordAuthentication getPasswordAuthentication() {
                    //The sender's account and password.
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            });
            //Create a mail object.
            MimeMessage message = new MimeMessage(session);
            //Set the email sender.
            InternetAddress from = new InternetAddress("sender_address","sender_name"); //The from parameter, which can be used for relaying. Note: Relayed emails are more likely to be rejected by the recipient's server or moved to the spam folder.
            message.setFrom(from);
            //Set the email recipients.
            String[] to = {"recipient_address_1","recipient_address_2","recipient_address_3"};//Recipient list.
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i=0;i<to.length;i++){
                //System.out.println("Sending to: " + to[i]);
                sendTo[i] = new InternetAddress(to[i]);
            }

            //Pass in the recipients.
            message.setRecipients(Message.RecipientType.TO,sendTo);
            //Set the email subject.
            message.setSubject("email_subject");
            //Set the email body.
            String content="email_body";
            message.setContent(content,"text/html;charset=UTF-8");
            //Set the time.
            message.setSentDate(new Date());
            message.saveChanges();
            //Send the email.
            Transport.send(message);
            System.out.println("Sent successfully!");
        }catch(Exception e){
            System.out.println("Exception: "+e.toString());
        }
    }
}

Connectivity test commands:

telnet smtp.qiye.aliyun.com 25

openssl s_client -connect smtp.qiye.aliyun.com:465 -crlf