javamail java mail sending tutorial

Javamail Tutorial

Try javamail today to send emails, javamail is still relatively powerful, let’s start the tutorial without talking nonsense!

The jar required by javamail copy the link to download

 http://download.csdn.net/detail/weixin_38111957/9851885

Below is the Dome of javamail

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Properties;

public class Main {
	
    // Sender's email and password (replace with your own email and password)
    // PS: In order to increase the security of the password of the mailbox itself, some mailbox servers set an independent password for the SMTP client (some mailboxes are called "authorization code"),
    // For mailboxes with an independent password enabled, the mailbox password here must use this independent password (authorization code).
    public static String myEmailAccount = "********";//Add your own mailbox number
    public static String myEmailPassword = "********";//This is the mailbox password, the password is the authorization code of the mailbox

    // The SMTP server address of the sender's mailbox must be accurate, different mail server addresses are different, the general (just general, not absolute) format is: smtp.xxx.com
    // The SMTP server address of Netease 163 mailbox is: smtp.163.com
    public static String myEmailSMTPHost = "smtp.qq.com";//Here is an example of qq mailbox

    // Recipient's email address (replace with a valid email address you know)
    public static String receiveMailAccount = "********";

    public static void main(String[] args) throws Exception {
    	  // 1. Create a parameter configuration for connecting to the mail server
        Properties props = new Properties(); // parameter configuration
        props.setProperty("mail.transport.protocol", "smtp"); // protocol used (required by JavaMail specification)
        props.setProperty("mail.smtp.host", myEmailSMTPHost); // SMTP server address of sender's mailbox
        props.setProperty("mail.smtp.auth", "true"); // requires authentication
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");


        // PS: Some mailbox servers require SMTP connection to use SSL security authentication (in order to improve security, the mailbox supports SSL connection, or you can open it yourself),
        // If you can't connect to the mail server, carefully check the log printed on the console, if there are errors like "Connection failed, SSL secure connection required", etc.,
        // Open the commented code between /* ... */ below to enable SSL secure connection.
        /*
        // The port of the SMTP server (the port of the non-SSL connection is generally 25 by default, you can not add it, if the SSL connection is enabled,
        // Need to be changed to the port of the SMTP server corresponding to the mailbox. For details, see the help of the corresponding mailbox service.
        // The SMTP (SLL) port of QQ mailbox is 465 or 587, other mailboxes can check by themselves)
        final String smtpPort = "465";
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
        */

        // 2. Create a session object based on the configuration to interact with the mail server
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true); // Set to debug mode, you can view the detailed sending log

        // 3. Create an email
        MimeMessage message = createMimeMessage(session, myEmailAccount, receiveMailAccount);

        // 4. Get the mail transfer object according to the Session
        Transport transport = session.getTransport();

        // 5. Use the email account and password to connect to the mail server. The authenticated email address here must be the same as the sender's email address in the message, otherwise an error will be reported
        //
        // PS_01: The key to success or failure is this sentence. If the connection to the server fails, the log of the corresponding failure reason will be output in the console.
        // Carefully check the reason for the failure, some mail servers will return an error code or view the link of the error type, according to the error given
        // Type to the help website of the corresponding mail server to check the specific failure reason.
        //
        // PS_02: The reason for the connection failure is usually the following, check the code carefully:
        // (1) The mailbox does not open the SMTP service;
        // (2) The mailbox password is wrong, for example, some mailboxes have independent passwords enabled;
        // (3) The mailbox server requires an SSL secure connection;
        // (4) The request is too frequent or other reasons, and the service is refused by the mail server;
        // (5) If the above points are all correct, go to the mail server website to find help.
        //
        // PS_03: Read the log carefully, read the log carefully, understand the log, and the cause of the error has been explained in the log.
        transport.connect(myEmailAccount, myEmailPassword);

        // 6. Send mail to all recipient addresses, message.getAllRecipients() gets all recipients, cc, and bcc added when the mail object was created
        transport.sendMessage(message, message.getAllRecipients());

        // 7. Close the connection
        transport.close();
    }
    
    /**
     * Create a simple email with only text
     *
     * @param session The session for interacting with the server
     * @param sendMail sender email
     * @param receiveMail recipient email
     * @return
     * @throws Exception
     */
    public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception {
        // 1. Create an email
        MimeMessage message = new MimeMessage(session);

        // 2. From: sender
        message.setFrom(new InternetAddress(sendMail, "某某某", "UTF-8"));

        // 3. To: recipient (multiple recipients can be added, cc, bcc)
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8"));

        // 4. Subject: the subject of the email
        message.setSubject("NB registration verification", "UTF-8");

        // 5. Content: The body of the email (html tags can be used)
        message.setContent("La la la la, congratulations on sending your email successfully!", "text/html;charset=UTF-8");

        // 6. Set the delivery time
        message.setSentDate (new Date ());

        // 7. Save settings
        message.saveChanges();

        return message;
    }

}

How to get the authorization code of the mailbox?

      1: Take QQ mailbox as an example, first log in to QQ mailbox, click Settings


2: Under the account, there is an open service setting, open these two services, you will see an authorization code, just copy it directly into the code.



OK, the tutorial is here, I wish you a happy Java study! ps: This is the first time for the editor to write a blog, and the shortcomings will be improved in the future!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325540619&siteId=291194637