当前位置:网站首页>Mail sending function is realized through SMTP protocol and exchange

Mail sending function is realized through SMTP protocol and exchange

2022-06-22 06:12:00 Dark night 91

Author's brief introduction :
author : Dark night 91
🤟 Personal home page : Dark night 91 The home page of
WeChat official account : Programmer's knowledge station , Follow my official account , Learn more cutting-edge knowledge .


SpringBoot adopt smtp The protocol and exchange There are two different ways to realize the mail sending function .

1、SMTP Deal with the Exchange

SMTP agreement :

SMTP The full name is “Simple Mail Transfer Protocol”, Simple Mail Transfer Protocol . It is a set of specifications used to transfer mail from source address to destination address , Through it to control the way of mail transfer . One of its important features is that it can relay mail during transmission , In other words, e-mail can be relayed through hosts on different networks .

SMTP authentication , In short, it requires that you must provide the account name and password before you can log in SMTP The server , This makes it impossible for spammers of spam . increase SMTP The purpose of authentication is to protect users from spam .SMTP It's a fact E-Mail Standards of transmission .

Exchange

Exchange Is a set of e-mail processing components launched by Microsoft , Also through smtp Protocol to send and receive mail .

2、 add to SMTP Mail sending dependency

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

3、 add to Exchange The agreement depends on

<dependency>
    <groupId>com.microsoft.ews-java-api</groupId>
    <artifactId>ews-java-api</artifactId>
    <version>2.0</version>
</dependency>

4、 Add mail configuration

#smtp Protocol configuration 
[email protected]
smtp.send.password=BSNLVRFYDUMBJYNF
smtp.send.host=smtp.163.com

#exchange Protocol configuration 
[email protected]
exchange.send.password=Abc123456
exchange.send.host=mail.xxx.com

5、 Add public interface

package com.lll.common.mail;

import lombok.extern.slf4j.Slf4j;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.FileAttachment;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.*;

@Slf4j
@Component
public class MailCommonService {
    

    /** * * @param toList  List of recipients  * @param mailSubject  Email subject  * @param contentList  Message body , In the order of the list , Show in email . *  When the message content has multiple lines , Each line is a MailContentVO * @param fileList  Absolute path of attachment file  * @param type  Mail protocol type  */
    public void sendMail(List<String> toList,String mailSubject,List<MailContentVO> contentList,List<String> fileList,MailProtocolType type) {
    
        try {
    
            Properties props = new Properties();
            ClassPathResource classPathResource = new ClassPathResource("/mail.properties");
            InputStream inputStream  = classPathResource.getInputStream();
            props.load(new InputStreamReader(inputStream, "UTF-8"));
            if (type.equals(MailProtocolType.smtp)){
    
                sendMailSmtp(toList,mailSubject,contentList,fileList,props);
            } else if(type.equals(MailProtocolType.exchange)){
    
                sendMailExchange(toList,mailSubject,contentList,fileList,props);
            } else {
    
                sendMailSmtp(toList,mailSubject,contentList,fileList,props);
            }
            log.info(" The mail is sent ......");
        } catch (IOException e) {
    
            e.printStackTrace();
        }

    }

    /** *  Send E-mail  * @param toList  List of recipients  * @param mailSubject  Email subject  * @param contentList  Message body , In the order of the list , Show in email . *  When the message content has multiple lines , Each line is a MailContentVO * @param fileList  Absolute path of attachment file  * @param properties  Send mailbox related configuration  */
    public void sendMailSmtp(List<String> toList, String mailSubject, List<MailContentVO> contentList, List<String> fileList, Properties properties) {
    
        String senderAddress = properties.getProperty("smtp.send.address");
        String senderPassword = properties.getProperty("smtp.send.password");
        try {
    
            //1、 Parameter configuration for connecting to the mail server 
            Properties props = new Properties();
            // Set the user's authentication mode 
            props.setProperty("mail.smtp.auth", "true");
            // Set up the transport protocol 
            props.setProperty("mail.transport.protocol", "smtp");
            // Set sender's SMTP Server address 
            props.setProperty("mail.smtp.host", properties.getProperty("smtp.send.host"));
            //2、 Create... That defines the environment information required for the entire application  Session  object 
            Session session = Session.getInstance(props);
            // Set the debug information to print out on the console 
            session.setDebug(true);
            //3、 Create instance objects for mail 
            Message msg = getMimeMessage(session,senderAddress,toList,mailSubject,contentList,fileList);
            //4、 according to session Object to get the mail transfer object Transport
            Transport transport = session.getTransport();
            // Set the sender's account name and password 
            transport.connect(senderAddress, senderPassword);
            // Send E-mail , If you only want to send it to the designated person , It can be written as follows 
            Address[] addresses = new Address[toList.size()];
            for (int i=0;i<toList.size();i++){
    
                addresses[i] = new InternetAddress(toList.get(i));
            }
            transport.sendMessage(msg, addresses);
            //5、 Close the mail connection 
            transport.close();

        } catch (Exception e) {
    
            e.printStackTrace();
        }
    }

    private MimeMessage getMimeMessage(Session session, String senderAddress, List<String> toList, String mailSubject, List<MailContentVO> contentList, List<String> fileList) throws Exception {
    
        //1、 Create a mail instance object 
        MimeMessage msg = new MimeMessage(session);
        //2、 Set the sender address 
        msg.setFrom(new InternetAddress(senderAddress));
        /** * 3、 Set recipient address ( Multiple recipients can be added 、 CC 、 Send off ), That is, the following line of code to write multiple lines  * MimeMessage.RecipientType.TO: send out  * MimeMessage.RecipientType.CC: CC  * MimeMessage.RecipientType.BCC: Send off  */
        for (String to:toList){
    
            msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
        }
        //4、 Set up email subject 
        msg.setSubject(mailSubject, "UTF-8");

        // 5、( Text + picture ) Set up   Text   and   picture " node " The relationship between ( take   Text   and   picture " node " Make a mixture " node ")
        MimeMultipart mm_text_image = new MimeMultipart();

        // Content combination of text nodes 
        List<String> textContent = new ArrayList<>();
        for (MailContentVO vo:contentList){
    
            MailContentType type = vo.getType();
            if (type.equals(MailContentType.txt)){
    
                textContent.add(vo.getContent());
            }else{
    
                String uid = UUID.randomUUID().toString();
                // Create a picture " node "
                MimeBodyPart image = new MimeBodyPart();
                // Read local file 
                DataHandler dh = new DataHandler(new FileDataSource(vo.getContent()));
                // Add image data to " node "
                image.setDataHandler(dh);
                // by " node " Set a unique number ( In the text " node " The ID)
                image.setContentID(uid);
                mm_text_image.addBodyPart(image);
                //
                String img = "<img src='cid:"+uid+"'/>";
                textContent.add(img);
            }
        }

        MimeBodyPart text = new MimeBodyPart();
        //  The way to add pictures here is to include the whole picture in the email content ,  In fact, we can also use  http  Add web pictures in the form of links 
        text.setContent(StringUtils.join(textContent,"<br/>"), "text/html;charset=UTF-8");
        mm_text_image.addBodyPart(text);
        mm_text_image.setSubType("related"); // Connections 

        // 8.  take   Text + picture   Mixing " node " Packaged as a normal " node "
        //  Finally added to the  Content  It's made up of many  BodyPart  Composed of  Multipart,  So what we need is  BodyPart,
        MimeBodyPart text_image = new MimeBodyPart();
        text_image.setContent(mm_text_image);

        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text_image);
        //9、 Set up attachment 
        for (String filePath:fileList){
    
            File file = new File(filePath);
            MimeBodyPart attachment = new MimeBodyPart();
            DataSource source = new FileDataSource(filePath);
            attachment.setDataHandler(new DataHandler(source));
            attachment.setFileName(MimeUtility.encodeText(file.getName()));
            mm.addBodyPart(attachment);
        }
        mm.setSubType("mixed");  //  Mixed relationship 
        // 10、  Set the relationship for the entire message ( Put the final mix " node " Add to the message object as the content of the message )
        msg.setContent(mm);
        // Set the sending time of the mail , Send immediately by default 
        msg.setSentDate(new Date());
        return msg;
    }

    /** *  Send E-mail  * @param toList  List of recipients  * @param subject  Email subject  * @param contentList  Message body , In the order of the list , Show in email . *  When the message content has multiple lines , Each line is a MailContentVO * @param filePath  Absolute path of attachment file  * @param properties  Send mailbox related configuration  */
    private void sendMailExchange(List<String> toList, String subject, List<MailContentVO> contentList, List<String> filePath, Properties properties)  {
    
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
        ExchangeCredentials credentials = new WebCredentials(properties.getProperty("exchange.send.address"),properties.getProperty("exchange.send.password"));
        service.setCredentials(credentials);
        try {
    
	        String uri = "https://"+properties.getProperty("exchange.send.host")+"/ews/exchange.asmx";
            service.setUrl(new URI(uri));
            EmailMessage msg = new EmailMessage(service);
            // Set up email subject 
            msg.setSubject(subject);

            // Set the message body 
            List<String> textContent = new ArrayList<>();
            for (MailContentVO vo:contentList){
    
                MailContentType type = vo.getType();
                if (type.equals(MailContentType.txt)){
    
                    textContent.add(vo.getContent());
                }else{
    
                    String uid = UUID.randomUUID().toString();
                    FileAttachment attachment = msg.getAttachments().addFileAttachment(vo.getContent());
                    attachment.setContentType("image");
                    attachment.setContentId(uid);
                    String img = "<img src='cid:"+uid+"'/>";
                    textContent.add(img);
                }
            }

            // Set email attachments 
            if (!CollectionUtils.isEmpty(filePath)){
    
                for (String path:filePath){
    
                    String uid = UUID.randomUUID().toString();
                    FileAttachment attachment1 = msg.getAttachments().addFileAttachment(path);
                    attachment1.setContentType("image");
                    attachment1.setContentId(uid);
                }
            }
            MessageBody body = MessageBody.getMessageBodyFromText(StringUtils.join(textContent,"<br/>")+"<hr/>");
            body.setBodyType(BodyType.HTML);
            msg.setBody(body);

            // Set up mail recipients 
            for (String to : toList) {
    
                msg.getToRecipients().add(to);
            }

            // Mail delivery 
            msg.send();
        } catch (Exception e) {
    
            log.error(e.getMessage(),e);
        }
    }
}

6、 Support protocol enumeration

public enum MailProtocolType {
    
    smtp,exchange;
}

7、 Message body content enumeration

public enum MailContentType {
    
    txt(" Text "),img(" picture ");
    private String type;
    MailContentType(String type) {
    
        this.type = type;
    }
}

8、 The body of the email

@Data
public class MailContentVO {
    

    /** *  Body information type  */
    private MailContentType type;

    /** *  textual information  * txt Content or img Absolute path  */
    private String content;

}

原网站

版权声明
本文为[Dark night 91]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220552131362.html