httpclient mail

package com.chuanglan;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Multipart;
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 javax.mail.internet.MimeUtility;

@Component
public class EmailClient {
    private static final Logger logger = LogManager.getLogger(EmailClient.class);
    @Autowired private EmailClientInfo clientInfo ;

    /**
     * 
     * @param info 邮件信息
     * @return 返回
     * @throws Exception exception
      * / 
    public  Boolean Send (MailInfo info) throws Exception { 
        logger.info (the clientInfo); 
        // 1. Create parameters, parameters for connection to the mail server configuration 
        the Properties The props = new new the Properties ();                     // Parameter configuration 
        props.setProperty ( "mail.transport.protocol", "SMTP");    // protocol (the JavaMail specifications) used 
        props.setProperty ( "the mail.smtp.host", clientInfo.getSmtpHost ());    // send SMTP server address members who mailbox 
        props.setProperty ( "mail.smtp.auth", "to true");             // need to request certification 

        // 2. create a session object depending on the configuration,And for the mail server interaction
        = The session the Session Session.getInstance (props); 
        session.setDebug ( to true );                                  // set to debug mode, you can view detailed sending log 

        // 3. create a message 
        the MimeMessage the Message = createMimeMessage (the session, info); 

        // 4. Session Object the Get message transfer 
        transport transport = Session.getTransport (); 

        // 5. the mailbox account and password to connect to the mail server where the mailbox must be consistent with the authentication message in the mailbox of the sender, otherwise an error
         //  
        / /     PS_01: determine the key to success in this way, if you connect to a server fails, the corresponding output in the console log reason for the failure,
         //            carefully review the reasons for the failure, some mail server returns an error code or viewing the wrong type of link, according to out error
         //           Type to the appropriate mail server to help the site to view specific reason for the failure.
        // 
        //     PS_02: why the connection failure is usually the following points carefully check the code:
         //            (1) does not turn on SMTP mail service;
         //            (2) mailbox password is wrong, for example, some mailboxes opened independent password;
         / /            (3) requires the mailbox server must use SSL secure connection;
         //            (4) requests too frequently or for other reasons, be denied service mail server;
         //            (5) to determine if the above points are correct, the mail server to find the site help.
        // 
        //     PS_03: look carefully log, take a good look log, read log, error reasons have been described in the log. 
        transport.connect (clientInfo.getSenderAddress (), clientInfo.getPassword ()); 

        // 6. send the message, sent to all recipient addresses, message.getAllRecipients () to get all the income is added when you create a message object people member, Cc, Bcc
        transport.sendMessage (the Message, message.getAllRecipients ()); 

        // 7. close the connection 
        transport.close ();
         return  to true ; 
    } 

    / ** 
     Simple Mail * Create a text contains only 
     * 
     * @param the session and server interaction the session 
     * @return return 
     * @throws Exception abnormal
      * / 
//     public static the MimeMessage createMimeMessage (the session the session, sendMail String, String the receiveMail) throws Exception { 
      public the MimeMessage createMimeMessage (the session the session, MailInfo info) throws Exception {
         // 1. create An email
        The Message = the MimeMessage new new the MimeMessage (the session); 

        // 2. the From: sender (nickname advertising suspects, to avoid being mistaken for junk mail servers as well as advertising returns a failure, modify the nickname) 
        message.setFrom ( new new InternetAddress (clientInfo .getSenderAddress (), clientInfo.getSenderName (), "UTF-. 8" )); 

        // 3. the To: To (multiple recipients can be increased, CC, BCC) 
        message.setRecipient (MimeMessage.RecipientType .TO, new new InternetAddress (info.getRecipientAddress (), info.getRecipientName (), "UTF-8" )); 

        // 4. Subject: message subject (title advertising suspects, the mail server to avoid being mistaken for spamming as well as failure to return, please change the title) 
        message.setSubject (info.getSubject (), "UTF-8" ); 

        // 5. content: body of the message (you can use html tags) (content advertising suspects, the mail server to avoid being mistaken considered spamming and even failed to return, please send the modified contents)
        message.setContent (info.getContent (), "text / HTML; charset = UTF-. 8" ); 

        // 6. The set time sender 
        message.setSentDate ( new new a Date ()); 
        
        IF ! (info.getFile () = null ) { 
            multipart multipart = new new MimeMultipart ();   
            the BodyPart Part = new new the MimeBodyPart ();  
             // get the data according to the file name of the source   
            the dataSource the dataSource = new new The FileDataSource (info.getFile ()); 
            the dataHandler dataHandler = new new the dataHandler (the dataSource);  
             / / to give to the attachment itself and BodyPart  
            part.setDataHandler (dataHandler);  
             // get the file name of the same to the BodyPart   
            part.setFileName (MimeUtility.encodeText (dataSource.getName ()));   
            multipart.addBodyPart (Part);   
            
            message.setContent (multipart); 
        } 
        
        // . 7 save settings 
        message.saveChanges (); 
        
        return Message; 
        
    } 
    
}

 

Guess you like

Origin www.cnblogs.com/muxi0407/p/11607037.html