1. Use javax.mail , javamailsender of spring, and springboot to send mail

xiaocantian 2020-11-09 14:08:06
use javax.mail javax mail javamailsender


One 、java email

  1. Email server : These mail servers are like post offices , It's the main user who delivers it , And deliver it to the recipient's email address , There are two types by function
    • SMTP Mail server : Users send mail for users and receive mail sent to local users from outside
    • POP3/IMAP Mail server : Users help users read SMTP The mail server receives incoming mail
  2. Mail Transfer Protocol : E-mail needs to be between the mail client and the mail server , And mail delivery between two mail servers , You have to follow certain rules
    • SMTP agreement : Its full name is Simple Mail Transfer Protocol, Simple mail transfer protocol . It defines mail client software and SMTP Between mail servers , And two SMTP Communication rules between mail servers
    • POP3 agreement : Its full name is Post Office Protocol, Post office protocol . It defines mail client software and POP3 Mail server communication rules
    • IMAP agreement : Its full name is Internet Message Access Protocol,Internet Message Access Protocol , It's right POP3 An extension of the protocol , It also defines the mail client software and IMAP Mail server communication rules
  3. Email format : The basic format and details of the content of the e-mail are provided by RFC822 Documentation and MIME The agreement defines
    • RFC822 The file format defined in the document consists of two parts : Header and body
    • ME agreement (Multipurpose Internet Mail Extensions ) The format used to define complex email bodies , Diversify your email content
  4. Email sending and receiving process
      • Mail client software to write an email , Deliver it to SMTP Of QQ Mail server
      • QQ The mailbox will parse the email sent by the user , Determine whether the receiving address is your own account , If the receipt is also QQ mailbox , Will be directly stored in their own storage space . If not QQ mailbox , It is 163 mailbox , that QQ The mailbox will forward the mail to 163 Mailbox server , So is the forwarding protocol SMTP
      • 163 Mailbox server received QQ Email forwarded from the mailbox , Will determine whether the receiving address is your own , If it's your own account , Will be QQ The mail forwarded by the mailbox is stored in its own internal storage space
      • user A After sending the mail , Inform the user of B Go to the designated mailbox to collect mail . user B Will be through the mail client software to 163 Mailbox server request , Ask for your own mail
      • 163 The mailbox server received the user B After request , Will take out of their own storage space B Unsolicited mail
      • 163 The mailbox server takes out the user B After the uncollected mail , Send email to users B, The last three steps users B The process of receiving mail , The protocol used is POP3

Two 、 Use javax.mail Send E-mail ( Simple , With pictures , With accessories , With pictures and accessories )

  • You should apply for qq Email authorization code ( When used by a third party , Alternative password )

  • qq Port and email address (smtp.qq.com port 465 or 587)

  • Import dependence

  • <!-- Sent by jar 1.4 The version will appear javamail.providers The document can't be found And others jar File conflict in package -->
    <dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.4</version>
    </dependency>
    
  1. Basic information class of e-mail

    @Data
    public class JavaMailInfo {
    /**
    * Use java mail Send E-mail The mail agreement is SMTP POP IMAP MIME etc. The specific content of the agreement can be Baidu SMTP For Simple Mail Transfer Protocol More commonly used
    */
    // Mail server address
    private String mailSeverHost;
    // Mail server port
    private String mailServerPort;
    // The sender of the mail
    private String fromAddress;
    // Sender user name
    private String userName;
    // Sender password
    private String password;
    // Addressee address
    private String toAddress;
    // Email subject
    private String subject;
    // Email content
    private String content;
    // Picture address set
    private List<String> photoUrlList;
    // Attachment address set
    private List<String> attachList;
    /**
    * Get email session properties , For email Session Set it up The content of this part can be set by loading the configuration file
    * @return
    */
    public Properties getProperties() {
    Properties properties = new Properties();
    properties.put("mail.transport.protocol", "smtp");// Connection protocol
    properties.put("mail.smtp.host", this.mailSeverHost);// Host name
    properties.put("mail.smtp.port", this.mailServerPort);// Port number
    properties.put("mail.smtp.auth", "true");// Set up smtp Is certification required
    properties.put("mail.smtp.ssl.enable", "true");// Set whether to use ssl A secure connection --- Generally used
    properties.put("mail.debug", "true");// Set whether to display debug Information true Relevant information is displayed in the console
    properties.put("mail.smtp.timeout", 20000);// Timeout time
    return properties;
    }
    }
    
  2. Authority authentication class

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class MyJavaMailAuthenticator extends Authenticator {
    private String userName = null;
    private String password = null;
    /**
    * This class is used to store the user name and password used for authorization For building mail Session object It is convenient to mail when authentication is needed Session Know which class validation to use
    * User name 、 Password access to protected resources , ad locum “ resources ” It's a mail server
    * Custom classes need to inherit Authenticator class rewrite getPasswordAuthentication() Method Pay attention to the guide bag Need to use javax.mail The related classes under package
    */
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(this.userName, this.password);
    }
    }
    
  3. Send mail tool class

    public class JavaMailSendUtils {
    /**
    * The actual use
    * @param args
    */
    public static void main(String[] args) {
    JavaMailInfo javaMailInfo = new JavaMailInfo();
    javaMailInfo.setMailSeverHost("smtp.qq.com");
    javaMailInfo.setMailServerPort("465");// 465 or 587( Use ssl)
    javaMailInfo.setFromAddress(" Sender ");
    javaMailInfo.setUserName(" Your email user name ");
    javaMailInfo.setPassword(" Your email authorization code ");// The password needs to use the authorization code of the corresponding mailbox
    javaMailInfo.setToAddress(" The recipient ");
    javaMailInfo.setSubject(" Email subject ");
    javaMailInfo.setContent(" Email content ");
    List<String> photoUrlList = new ArrayList<>();
    photoUrlList.add(" picture 1");
    photoUrlList.add(" picture 2");
    javaMailInfo.setPhotoUrlList(photoUrlList);
    List<String> attachList = new ArrayList<>();
    attachList.add(" The attachment 1");
    attachList.add(" The attachment 2");
    javaMailInfo.setAttachList(attachList);
    sendJavaMail(javaMailInfo);
    }
    /**
    * This tool class can send mail according to the basic information of mail
    */
    /**
    * How to send email
    * @param javaMailInfo
    * @return
    */
    public static boolean sendJavaMail(JavaMailInfo javaMailInfo) {
    // Get mail session Related configuration parameters of
    Properties properties = javaMailInfo.getProperties();
    // Create authorization validation class
    MyJavaMailAuthenticator myJavaMailAuthenticator = new MyJavaMailAuthenticator();
    myJavaMailAuthenticator.setUserName(javaMailInfo.getUserName());
    myJavaMailAuthenticator.setPassword(javaMailInfo.getPassword());
    // Build mail Session Conversation object With or without default All possible See the source code belt default Is to get the properties of this class What's not retrieved is newly created
    Session mailSession = Session.getDefaultInstance(properties, myJavaMailAuthenticator);
    // Turn on debug properties If it is set in, there is no need to set it here
    // mailSession.setDebug(true);
    // Postman object You can also use static methods to send
    Transport transport = null;
    try {
    // Get message That's what you're sending
    // Message message = createSimpleMail(mailSession, javaMailInfo);
    // Message message = createImageMail(mailSession, javaMailInfo);
    // Message message = createAttachMail(mailSession, javaMailInfo);
    Message message = createPhotoAndAttachMail(mailSession, javaMailInfo);
    // Set the specification What are the specific norms ? Fixed writing
    MailcapCommandMap defaultCommandMap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    defaultCommandMap.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    defaultCommandMap.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    defaultCommandMap.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    defaultCommandMap.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    defaultCommandMap.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(defaultCommandMap);
    // Send E-mail Transport.send(message); Or get Transport Object to send
    transport = mailSession.getTransport();
    transport.connect(javaMailInfo.getUserName(), javaMailInfo.getUserName());
    transport.sendMessage(message, message.getAllRecipients());
    System.out.println(" Mail sent successfully ");
    return true;
    } catch (MessagingException e) {
    e.printStackTrace();
    System.out.println(" Failed to send mail ");
    return false;
    } finally {
    if (null != transport) {
    try {
    transport.close();
    } catch (MessagingException e) {
    e.printStackTrace();
    }
    }
    }
    }
    /**
    * According to the mail Session And email information to create email content ( The text class html)
    * @param mailSession
    * @param javaMailInfo
    * @return
    */
    private static Message createSimpleMail(Session mailSession, JavaMailInfo javaMailInfo) throws MessagingException {
    /**
    * Message It's one An abstract class , We use MimeMessage This subclass , This class uses MIME type 、MIME Information header Email information
    * The header can only be used US-ASCII character , Instead of ASCII Characters will be encoded into ASCII The way to use
    */
    // According to the mail session Create message object
    MimeMessage mimeMessage = new MimeMessage(mailSession);
    // Set sender setFrom and setReplyTo All possible There are multiple senders using addFroms(Address[] addresses)
    mimeMessage.setFrom(new InternetAddress(javaMailInfo.getFromAddress()));
    // Set up recipients Recipient type Message.RecipientType.TO( The recipient ) Message.RecipientType.CC( With a copy of ) Message.RecipientType.BCC( The messenger )
    // setRecipients(Message.RecipientType var1, Address[] var2) Set up multiple recipients
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(javaMailInfo.getToAddress()));
    // Set title
    mimeMessage.setSubject(javaMailInfo.getSubject(), "text/plain;charset=utf-8");
    // Set contents It's text that can be used directly setText()
    mimeMessage.setContent(javaMailInfo.getContent(), "text/html;charset=utf-8");
    // Set send time
    mimeMessage.setSentDate(new Date());
    mimeMessage.saveChanges();
    return mimeMessage;
    }
    /**
    * According to the mail Session And email information to create email content ( Picture class There can be multiple pictures )
    * @param mailSession
    * @param javaMailInfo
    * @return
    */
    private static Message createImageMail(Session mailSession, JavaMailInfo javaMailInfo) throws MessagingException {
    /**
    * Message It means an email ,messgaes.getContent() Return to one Multipart object . One Multipart Object contains one or more BodyPart object , To make up the body of the email ( Including accessories )
    * Multipart Of content-type
    * On the whole ,MIME A message consists of a header and a body . Now we're focusing on MIME mail , Therefore, in the following discussion, let's call it “ news ” by “ mail ”.
    * The header contains the sender 、 The recipient 、 The theme 、 Time 、MIME edition 、 Important information such as the type of email content . Each piece of information is called a domain , Add... After the domain name “: ” And information content , It can be a line of , Longer ones can also take up more than one line .
    * The first line of the field must be “ Head ” Write , That is, there must be no blank characters on the left ( Spaces and tabs ); The continuation line must start with a blank character , And the first blank character is not inherent in the message itself , Filter out when decoding .
    * The body of the email contains the content of the message , Its type is determined by the header's “Content-Type” The field indicates that . Common simple types are text/plain( Pure text ) and text/html( Hypertext ). Sometimes it happens multipart type , yes MIME The essence of email .
    * The body of the message is divided into segments , Each segment includes two parts: the segment head and the segment body , The two parts are also separated by blank lines . common multipart There are three types :multipart/mixed, multipart/related and multipart/alternative.
    * multipart/mixed: The attachment .
    * multipart/related: embedded resource .
    * multipart/alternative: Pure text and hypertext coexist .
    */
    MimeMessage mimeMessage = new MimeMessage(mailSession);
    mimeMessage.setFrom(new InternetAddress(javaMailInfo.getFromAddress()));
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(javaMailInfo.getToAddress()));
    mimeMessage.setSubject(javaMailInfo.getSubject(), "text/plain;charset=utf-8");
    List<String> photoUrlList = javaMailInfo.getPhotoUrlList();
    // Create message body In the following way, each picture has a title
    MimeMultipart mimeMultipart = new MimeMultipart();
    if (!CollectionUtils.isEmpty(photoUrlList)) {
    for (String photoUrl : photoUrlList) {
    MimeBodyPart text = new MimeBodyPart();
    // Set picture title Be careful img The reference position of the tag use cid: start
    String cid = UUID.randomUUID().toString();
    text.setContent(javaMailInfo.getContent() +"<br/><img src='cid:"+ cid +".jpg'>", "text/html;charset=utf-8");
    // Use a data processor to process pictures
    MimeBodyPart image = new MimeBodyPart();
    image.setDataHandler(new DataHandler(new FileDataSource(photoUrl)));
    image.setContentID(cid);
    // Describe the relationship between the text and the picture
    MimeMultipart photo = new MimeMultipart();
    photo.addBodyPart(text);
    photo.addBodyPart(image);
    photo.setSubType("related");
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(photo);
    // Put the picture in body in
    mimeMultipart.addBodyPart(mimeBodyPart);
    }
    }
    /*// In the following way, all pictures share a common title
    MimeMultipart photo = new MimeMultipart();
    MimeBodyPart text = new MimeBodyPart();
    photo.addBodyPart(text);
    StringBuilder textContent = new StringBuilder(javaMailInfo.getContent());
    if (!CollectionUtils.isEmpty(photoUrlList)) {
    for (String photoUrl : photoUrlList) {
    // Set picture title Be careful img The reference position of the tag use cid: start
    String cid = UUID.randomUUID().toString();
    textContent.append("<br/><img src='cid:"+ cid +".jpg'>");
    // Use a data processor to process pictures
    MimeBodyPart image = new MimeBodyPart();
    image.setDataHandler(new DataHandler(new FileDataSource(photoUrl)));
    image.setContentID(cid);
    // Describe the relationship between the text and the picture
    photo.addBodyPart(image);
    }
    photo.setSubType("related");
    }
    text.setContent(textContent.toString(), "text/html;charset=utf-8");*/
    // Set message body
    mimeMessage.setContent(mimeMultipart);
    // mimeMessage.setContent(photo);
    mimeMessage.setSentDate(new Date());
    mimeMessage.saveChanges();
    return mimeMessage;
    }
    /**
    * According to the mail Session And email information to create email content ( Annex Multiple attachments are available )
    * @param mailSession
    * @param javaMailInfo
    * @return
    */
    private static Message createAttachMail(Session mailSession, JavaMailInfo javaMailInfo) throws MessagingException {
    MimeMessage mimeMessage = new MimeMessage(mailSession);
    mimeMessage.setFrom(new InternetAddress(javaMailInfo.getFromAddress()));
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(javaMailInfo.getToAddress()));
    mimeMessage.setSubject(javaMailInfo.getSubject(), "text/plain;charset=utf-8");
    List<String> attachList = javaMailInfo.getAttachList();
    // Create message body
    MimeMultipart mimeMultipart = new MimeMultipart();
    MimeBodyPart text = new MimeBodyPart();
    text.setContent(javaMailInfo.getSubject(), "text/html;charset=utf-8");
    mimeMultipart.addBodyPart(text);
    if (!CollectionUtils.isEmpty(attachList)) {
    for (String attach : attachList) {
    // Create attachments
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    DataHandler dataHandler = new DataHandler(new FileDataSource(attach));
    mimeBodyPart.setDataHandler(dataHandler);
    mimeBodyPart.setFileName(dataHandler.getName());
    // Add the outermost container
    mimeMultipart.addBodyPart(mimeBodyPart);
    }
    // Descriptive relationship
    mimeMultipart.setSubType("mixed");
    }
    mimeMessage.setContent(mimeMultipart);
    mimeMessage.setSentDate(new Date());
    mimeMessage.saveChanges();
    return mimeMessage;
    }
    /**
    * According to the mail Session And email information to create email content ( More pictures Multiple accessories )
    * @param mailSession
    * @param javaMailInfo
    * @return
    */
    private static Message createPhotoAndAttachMail(Session mailSession, JavaMailInfo javaMailInfo) throws MessagingException {
    MimeMessage mimeMessage = new MimeMessage(mailSession);
    mimeMessage.setFrom(new InternetAddress(javaMailInfo.getFromAddress()));
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(javaMailInfo.getToAddress()));
    List<String> photoUrlList = javaMailInfo.getPhotoUrlList();
    // Get all the pictures Share a theme
    MimeMultipart photo = new MimeMultipart();
    MimeBodyPart text = new MimeBodyPart();
    photo.addBodyPart(text);
    StringBuilder textContent = new StringBuilder(javaMailInfo.getContent());
    if (!CollectionUtils.isEmpty(photoUrlList)) {
    for (String photoUrl : photoUrlList) {
    // Set picture title Be careful img The reference position of the tag use cid: start
    String cid = UUID.randomUUID().toString();
    textContent.append("<br/><img src='cid:"+ cid +".jpg'>");
    // Use a data processor to process pictures
    MimeBodyPart image = new MimeBodyPart();
    image.setDataHandler(new DataHandler(new FileDataSource(photoUrl)));
    image.setContentID(cid);
    // Describe the relationship between the text and the picture
    photo.addBodyPart(image);
    }
    photo.setSubType("related");
    }
    text.setContent(textContent.toString(), "text/html;charset=utf-8");
    // Wrap the picture into a body As Its content
    MimeBodyPart content = new MimeBodyPart();
    content.setContent(photo);
    // Get all the attachments
    List<String> attachList = javaMailInfo.getAttachList();
    MimeMultipart attach = new MimeMultipart();
    if (!CollectionUtils.isEmpty(attachList)) {
    for (String attachUrl : attachList) {
    // Create attachments
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    DataHandler dataHandler = new DataHandler(new FileDataSource(attachUrl));
    mimeBodyPart.setDataHandler(dataHandler);
    mimeBodyPart.setFileName(dataHandler.getName());
    // Add the outermost container
    attach.addBodyPart(mimeBodyPart);
    }
    }
    // The picture body and Accessories combination
    attach.addBodyPart(content);
    attach.setSubType("mixed");
    mimeMessage.setContent(attach);
    mimeMessage.setSentDate(new Date());
    mimeMessage.saveChanges();
    return mimeMessage;
    }
    }
    

3、 ... and 、 Use spring Of JavaMailSender Send E-mail ( Simple , With pictures , With accessories , With pictures and accessories ,freemarker Templates )

  • spring Provided JavaMailSender It's about the original javax.mail simplified

  • In the process of using it, you can register with spring In the container , You don't have to register

  • Import dependence

  • javax.mail The dependency package of
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    </dependency>
    
  1. Basic information class of e-mail

    @Data
    public class JavaMailSenderInfo {
    // Addressee address
    private String toAddress;
    // Email subject
    private String subject;
    // Email content
    private String content;
    // Whether it is html Note the fields boolean type Do not use is start idea Will generate get,set The method will be optimized isHtml -> isHtml(),getHtml() -- html -> isHtml(),getHtml()
    private boolean html = false;
    // Picture address set
    private List<String> photoList;
    // Attachment address set
    private List<String> attachList;
    }
    
  2. Get ready mail.propertise The configuration file ( That is to set the properties of the session ), Files in resource Under the table of contents

    # Transfer protocol
    mail.transport.protocol=smtp
    # Server hostname
    mail.smtp.host=smtp.qq.com
    # Server port number 465 or 587( Use ssl)
    mail.smtp.port=465
    # Whether to check the user name and password Is it configured You can't configure User name and password Otherwise, it will get the user name and password for verification
    mail.smtp.auth=true
    # Set whether to use ssl A secure connection --- Generally used
    mail.smtp.ssl.enable=true
    # Set whether to display debug Information true Relevant information is displayed in the console
    mail.debug=true
    # Set timeout
    mail.smtp.timeout=20000
    # Coding format
    mail.smtp.defaultEncoding=utf-8
    # Your email address
    mail.smtp.username=xxxxxx@qq.com
    # Your authorization code ( Third party uses era password )
    mail.smtp.password=xxxxxx
    
  3. Load profile , initialization JavaMailSender

    public class InitJavaMailSender {
    /**
    * The purpose of this class is to load a configuration file to create JavaMailSender object JavaMailSenderImpl Is the implementation class of the interface
    * So we need to be right about JavaMailSenderImpl To configure stay spring Under the environment of We can use the way to load the configuration file perhaps
    * stay spring Configure the... Directly in the configuration file bean( from spring trusteeship ) When using @Autowired Just inject it directly
    * <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    * <property name="host" value="${mail.smtp.host}" />
    * <property name="username" value="${mail.smtp.username}" />
    * <property name="password" value="${mail.smtp.password}" />
    * <property name="defaultEncoding" value="${mail.smtp.defaultEncoding}" />
    * <property name="javaMailProperties">
    * <props>
    * <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
    * <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
    * ...
    * </props>
    * </property>
    * </bean>
    * This time, the configuration file is loaded
    * from spring Provide The bottom layer is still javax.mail Send the email
    * JavaMailSenderImpl rely on javax.mail and spring-context-support package
    */
    // Transfer protocol
    private static String protocol;
    // Server hostname
    private static String host;
    // Server port number
    private static String port;
    // Whether to check the user name and password
    private static String auth;
    // Set whether to use ssl A secure connection
    private static String enableSSL;
    // Set whether to display debug Information
    private static String debug;
    // Timeout time
    private static String timeout;
    // Coding format
    private static String defaultEncoding;
    // Email address
    public static String username;
    // Authorization code
    private static String password;
    private static JavaMailSenderImpl javaMailSenderImpl;
    static {
    init();
    }
    private static void init() {
    // Load profile
    Properties properties = new Properties();
    InputStream resourceAsStream = JavaMailSender.class.getClassLoader().getResourceAsStream("mail.properties");
    try {
    properties.load(resourceAsStream);
    protocol = properties.getProperty("mail.transport.protocol");
    host = properties.getProperty("mail.smtp.host");
    port = properties.getProperty("mail.smtp.port");
    auth = properties.getProperty("mail.smtp.auth");
    enableSSL = properties.getProperty("mail.smtp.ssl.enable");
    debug = properties.getProperty("mail.debug");
    timeout = properties.getProperty("mail.smtp.timeout");
    defaultEncoding = properties.getProperty("mail.smtp.defaultEncoding");
    username = properties.getProperty("mail.smtp.username");
    password = properties.getProperty("mail.smtp.password");
    System.out.println("mail.properties Loading successful ");
    } catch (IOException e) {
    e.printStackTrace();
    System.out.println("mail.properties Loading failed ");
    } finally {
    if (null != resourceAsStream) {
    try {
    resourceAsStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
    /**
    * Use singleton to get JavaMailSender Double checking ensures thread safety It also ensures efficiency It can also delay loading
    * @return
    */
    public static JavaMailSender getJavaMailSender() {
    if (null == javaMailSenderImpl) {
    synchronized (InitJavaMailSender.class) {
    if (null == javaMailSenderImpl) {
    javaMailSenderImpl = new JavaMailSenderImpl();
    javaMailSenderImpl.setProtocol(protocol);
    javaMailSenderImpl.setHost(host);
    javaMailSenderImpl.setPort(Integer.parseInt(port));
    javaMailSenderImpl.setDefaultEncoding(defaultEncoding);
    javaMailSenderImpl.setUsername(username);
    javaMailSenderImpl.setPassword(password);
    Properties properties = new Properties();
    properties.setProperty("mail.smtp.auth", auth);
    properties.setProperty("mail.smtp.ssl.enable", enableSSL);
    properties.setProperty("mail.debug", debug);
    properties.setProperty("mail.smtp.timeout", timeout);
    javaMailSenderImpl.setJavaMailProperties(properties);
    }
    }
    }
    return javaMailSenderImpl;
    }
    }
    
  4. Email sending tool class

    public class JavaMailSenderUtils {
    /**
    * Test sending email In fact, it can be done in service Use in ( If you use spring How to configure the way to create JavaMailSender, It needs to be injected )
    * This is for ease of use main Method
    * @param args
    */
    public static void main(String[] args) {
    JavaMailSenderInfo javaMailSenderInfo = new JavaMailSenderInfo();
    javaMailSenderInfo.setToAddress(" Sender ");
    javaMailSenderInfo.setSubject(" Email subject ");
    javaMailSenderInfo.setContent(" Email content ");
    javaMailSenderInfo.setHtml(true);
    List<String> list = new ArrayList<>();
    list.add(" picture 1");
    // list.add(" picture 2");
    // list.add(" picture 3");
    // list.add(" picture 4");
    javaMailSenderInfo.setPhotoList(list);
    javaMailSenderInfo.setAttachList(list);
    // JavaMailSenderUtils.sendSimpleMail(javaMailSenderInfo);
    JavaMailSenderUtils.sendPhotoMail(javaMailSenderInfo);
    // JavaMailSenderUtils.sendAttacheMail(javaMailSenderInfo);
    // JavaMailSenderUtils.sendPhotoAndAttacheMail(javaMailSenderInfo);
    }
    private static final JavaMailSender javaMailSender = InitJavaMailSender.getJavaMailSender();
    private static final String htmlStartStr = "<html><body>";
    private static final String htmlEndStr = "</body></html>";
    /**
    * Send a simple email Text html
    * @param javaMailSenderInfo
    * @return
    */
    public static boolean sendSimpleMail(JavaMailSenderInfo javaMailSenderInfo) {
    // Create a mail message Simple mail can be used directly SimpleMailMessage
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = null;
    try {
    // Create a message helper Parameter two by true Multi component html etc.
    mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    // Set public fields
    setMailCommonField(mimeMessageHelper, javaMailSenderInfo);
    // Text content You can specify whether it is html
    mimeMessageHelper.setText(javaMailSenderInfo.getContent(), javaMailSenderInfo.isHtml());
    javaMailSender.send(mimeMessage);
    System.out.println(" Simple mail sent successfully ");
    return true;
    } catch (MessagingException e) {
    e.printStackTrace();
    System.out.println(" Simple Mail failed to send ");
    return false;
    }
    }
    /**
    * Send an email with pictures
    * @param javaMailSenderInfo
    * @return
    */
    public static boolean sendPhotoMail(JavaMailSenderInfo javaMailSenderInfo) {
    // Create a mail message Simple mail can be used directly SimpleMailMessage
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = null;
    try {
    mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    setMailCommonField(mimeMessageHelper, javaMailSenderInfo);
    List<String> photoList = javaMailSenderInfo.getPhotoList();
    // html Content
    StringBuilder text = new StringBuilder(htmlStartStr);
    text.append(javaMailSenderInfo.getContent());
    if (!CollectionUtils.isEmpty(photoList)) {
    for (String photo : photoList) {
    // Create a title for each image Each picture is associated with a cid
    String cid = UUID.randomUUID().toString();
    text.append("<br/><h1>"+ javaMailSenderInfo.getSubject() +"</h1><br/><img src='cid:"+ cid +"'/>");
    mimeMessageHelper.addInline(cid, new File(photo));
    }
    }
    // Why does the last picture split not show the problem ( Ask the boss for advice )
    // String cid = UUID.randomUUID().toString();
    // mimeMessageHelper.addInline(cid, new File(""));
    text.append(htmlEndStr);
    mimeMessageHelper.setText(text.toString(),true);
    javaMailSender.send(mimeMessage);
    System.out.println(" Email with picture sent successfully ");
    return true;
    } catch (MessagingException e) {
    e.printStackTrace();
    System.out.println(" Failed to send email with picture ");
    return false;
    }
    }
    /**
    * Send email with attachments
    * @param javaMailSenderInfo
    * @return
    */
    public static boolean sendAttacheMail(JavaMailSenderInfo javaMailSenderInfo) {
    // Create a mail message Simple mail can be used directly SimpleMailMessage
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = null;
    try {
    mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    setMailCommonField(mimeMessageHelper, javaMailSenderInfo);
    List<String> attachList = javaMailSenderInfo.getAttachList();
    // Email text
    mimeMessageHelper.setText(javaMailSenderInfo.getContent(), javaMailSenderInfo.isHtml());
    if (!CollectionUtils.isEmpty(attachList)) {
    for (String attach : attachList) {
    // Add attachments ( The last attachment is that pictures also have the problem of picture cracking , But it can be downloaded and used , Ask the boss for advice )
    FileSystemResource fileSystemResource = new FileSystemResource(attach);
    // Parameter 1 is the name of the attachment
    mimeMessageHelper.addAttachment(fileSystemResource.getFilename(), fileSystemResource);
    }
    }
    javaMailSender.send(mimeMessage);
    System.out.println(" Email with attachment sent successfully ");
    return true;
    } catch (MessagingException e) {
    e.printStackTrace();
    System.out.println(" Failed to send email with attachment ");
    return false;
    }
    }
    /**
    * Send email with pictures and attachments
    * @param javaMailSenderInfo
    * @return
    */
    public static boolean sendPhotoAndAttacheMail(JavaMailSenderInfo javaMailSenderInfo) {
    // Create a mail message Simple mail can be used directly SimpleMailMessage
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = null;
    try {
    mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    setMailCommonField(mimeMessageHelper, javaMailSenderInfo);
    List<String> photoList = javaMailSenderInfo.getPhotoList();
    // Put in pictures and content
    StringBuilder text = new StringBuilder(htmlStartStr + javaMailSenderInfo.getContent());
    if (!CollectionUtils.isEmpty(photoList)) {
    for (String photo : photoList) {
    String cid = UUID.randomUUID().toString();
    text.append("<br/><img src='cid:"+ cid +"'>");
    mimeMessageHelper.addInline(cid, new File(photo));
    }
    }
    text.append(htmlEndStr);
    mimeMessageHelper.setText(text.toString(),true);
    // Put in the attachment
    List<String> attachList = javaMailSenderInfo.getAttachList();
    if (!CollectionUtils.isEmpty(attachList)) {
    for (String attach : attachList) {
    // Add attachments
    FileSystemResource fileSystemResource = new FileSystemResource(attach);
    // Parameter 1 is the name of the attachment
    mimeMessageHelper.addAttachment(fileSystemResource.getFilename(), fileSystemResource);
    }
    }
    javaMailSender.send(mimeMessage);
    System.out.println(" Email with pictures and attachments sent successfully ");
    return true;
    } catch (MessagingException e) {
    e.printStackTrace();
    System.out.println(" Failed to send email with pictures and attachments ");
    return false;
    }
    }
    /**
    * Sent by freemarker Template technology generated mail
    * @param javaMailSenderInfo
    * @return
    */
    public static boolean sendFreemarkerMail(JavaMailSenderInfo javaMailSenderInfo) {
    // Create a mail message Simple mail can be used directly SimpleMailMessage
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = null;
    try {
    mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
    setMailCommonField(mimeMessageHelper, javaMailSenderInfo);
    /**
    * There is no implementation here using template technology ( You can explore for yourself )
    * Encapsulate the data required by the template
    * Read freemarker Template file xxx.ftl Make it static , Generate html String of form
    * Will generate a good html Set the string to the body of the message
    */
    javaMailSender.send(mimeMessage);
    System.out.println("freemarker The email generated by template technology was sent successfully ");
    return true;
    } catch (MessagingException e) {
    e.printStackTrace();
    System.out.println("freemarker The email generated by template technology failed to send ");
    return false;
    }
    }
    /**
    * Set the public fields of the mail
    * @param mimeMessageHelper
    * @param javaMailSenderInfo
    * @throws MessagingException
    */
    private static void setMailCommonField(MimeMessageHelper mimeMessageHelper, JavaMailSenderInfo javaMailSenderInfo) throws MessagingException {
    // Sender
    mimeMessageHelper.setFrom(InitJavaMailSender.username);
    // The recipient Multiplayer array
    mimeMessageHelper.setTo(javaMailSenderInfo.getToAddress());
    // The theme
    mimeMessageHelper.setSubject(javaMailSenderInfo.getSubject());
    // date
    mimeMessageHelper.setSentDate(new Date());
    }
    }
    

Four 、 Use springboot Send E-mail

  • Use springboot Send mail and use spring Provided JavaMailSender Send the email the same way

  • stay yml After configuring the relevant session information in the configuration file

  • stay service It can be injected directly into the layer

  • Import dependence

  • <!--springboot Integrate mail-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    
  1. Modify the configuration

    # Email settings Import mail Start the package Inject directly when using JavaMailSender that will do
    spring:
    mail:
    protocol: smtp
    host: smtp.qq.com
    port: 465
    default-encoding: utf-8
    username: Mailbox username
    password: Email authorization code
    test-connection: true
    properties:
    mail:
    debug: true
    smtp:
    auth: true
    timeout: 20000
    ssl:
    enable: true
    
  2. Directly in service Layer can be used

    public MailServiceImpl {
    @Autowired
    private JavaMailSender javaMailSender;
    // The following code can be used
    ...
    }
    
版权声明
本文为[xiaocantian]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云