springMVC simple implementation of sending mail

  • 2020-06-23 00:32:43
  • OfStack

Use ES1en. mail to send email, pictures and attachments can be sent

1, Controller class


package com.web.controller.api;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.service.EmailService;

@Controller
@RequestMapping("api")
public class EmailTaskController {

  private static final Logger logger = LoggerFactory.getLogger(EmailTaskController.class);

  @Resource 
  EmailService emailService;
  
  @RequestMapping("sendEmailTask")
  public void sendEmailTask() {
    logger.info("------------- Execute send message START---------------");
      // write excel
      //insuranceService.excelManage();
      // email 
      emailService.emailManage();
    
    logger.info("------------- Execute send message END---------------");
    
  }

}

2, service class


package com.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.entity.MailModel;
import com.service.EmailService;
import com.SimpleException;

@Service
public class EmailServiceImpl implements EmailService {
  private static Logger logger = Logger.getLogger(EmailServiceImpl.class);

  private String excelPath = "d://";
  
  @Resource
  private JavaMailSender javaMailSender;
  
  @Resource
  private SimpleMailMessage simpleMailMessage;
  
  @Override
  public void emailManage(){
    MailModel mail = new MailModel();
    // The theme 
    mail.setSubject(" listing "); 
    
    // The attachment 
    Map<String, String> attachments = new HashMap<String, String>();
    attachments.put(" listing .xlsx",excelPath+" listing .xlsx");
    mail.setAttachments(attachments);
    
    // content 
    StringBuilder builder = new StringBuilder();
    builder.append("<html><body> Hello! <br />");
    builder.append("&nbsp&nbsp&nbsp&nbsp The attachment is a personal list. <br />");
    builder.append("&nbsp&nbsp&nbsp&nbsp Personal information; <br />");
    builder.append("</body></html>");
    String content = builder.toString();
    
    mail.setContent(content);
    
    sendEmail(mail);
  }



  /**
   *  Send E-mail 
   * 
   * @author chenyq
   * @date 2016-5-9  In the morning 11:18:21
   * @throws Exception
   */
  @Override
  public void sendEmail(MailModel mail) {
    //  Create mail message 
    MimeMessage message = javaMailSender.createMimeMessage();
    
    MimeMessageHelper messageHelper;
    try {
      messageHelper = new MimeMessageHelper(message, true, "UTF-8");
      //  Set the sender email address 
      if (mail.getEmailFrom()!=null) {
        messageHelper.setFrom(mail.getEmailFrom());
      } else {
        messageHelper.setFrom(simpleMailMessage.getFrom());
      }
      
      //  Set the recipient mailbox 
      if (mail.getToEmails()!=null) {
        String[] toEmailArray = mail.getToEmails().split(";");
        List<String> toEmailList = new ArrayList<String>();
        if (null == toEmailArray || toEmailArray.length <= 0) {
          throw new SimpleException(" The recipient's mailbox must not be empty! ");
        } else {
          for (String s : toEmailArray) {
            if (s!=null&&!s.equals("")) {
              toEmailList.add(s);
            }
          }
          if (null == toEmailList || toEmailList.size() <= 0) {
            throw new SimpleException(" The recipient's mailbox must not be empty! ");
          } else {
            toEmailArray = new String[toEmailList.size()];
            for (int i = 0; i < toEmailList.size(); i++) {
              toEmailArray[i] = toEmailList.get(i);
            }
          }
        }
        messageHelper.setTo(toEmailArray);
      } else {
        messageHelper.setTo(simpleMailMessage.getTo());
      }
      
      //  Email subject 
      if (mail.getSubject()!=null) {
        messageHelper.setSubject(mail.getSubject());
      } else {
        
        messageHelper.setSubject(simpleMailMessage.getSubject());
      }
      
      // true  Said to start HTML Formatted email 
      messageHelper.setText(mail.getContent(), true);
      
      //  Add images 
      if (null != mail.getPictures()) {
        for (Iterator<Map.Entry<String, String>> it = mail.getPictures().entrySet()
            .iterator(); it.hasNext();) {
          Map.Entry<String, String> entry = it.next();
          String cid = entry.getKey();
          String filePath = entry.getValue();
          if (null == cid || null == filePath) {
            throw new RuntimeException(" Please confirm each picture ID And the picture address is complete! ");
          }
          
          File file = new File(filePath);
          if (!file.exists()) {
            throw new RuntimeException(" The picture " + filePath + " Does not exist! ");
          }
          
          FileSystemResource img = new FileSystemResource(file);
          messageHelper.addInline(cid, img);
        }
      }
      
      //  Add attachments 
      if (null != mail.getAttachments()) {
        for (Iterator<Map.Entry<String, String>> it = mail.getAttachments()
            .entrySet().iterator(); it.hasNext();) {
          Map.Entry<String, String> entry = it.next();
          String cid = entry.getKey();
          String filePath = entry.getValue();
          if (null == cid || null == filePath) {
            throw new RuntimeException(" Please confirm each attachment ID And the address is complete! ");
          }
          
          File file = new File(filePath);
          if (!file.exists()) {
            throw new RuntimeException(" The attachment " + filePath + " Does not exist! ");
          }
          
          FileSystemResource fileResource = new FileSystemResource(file);
          messageHelper.addAttachment(cid, fileResource);
        }
      }
      messageHelper.setSentDate(new Date());
      //  Send E-mail 
      javaMailSender.send(message);
      logger.info("------------ Completion of sending mail ----------");
      
    } catch (MessagingException e) {
      
      e.printStackTrace();
    }
  }

}

MailModel entity class


package com.support.entity;

import java.util.Map;

public class MailModel {
  
  /**
   *  Sender email server 
   */
  private String emailHost;
  /**
   *  Sender email 
   */
  private String emailFrom;

  /**
   *  Sender username 
   */
  private String emailUserName;

  /**
   *  Sender password 
   */
  private String emailPassword;

  /**
   *  Recipient mailbox, multiple mailboxes with the ; "Space 
   */
  private String toEmails;
  /**
   *  Email subject 
   */
  private String subject;
  /**
   *  Email content 
   */
  private String content;
  /**
   *  The picture in the email is empty and there is no picture. map In the key For the picture ID . value Is the image address 
   */
  private Map<String, String> pictures;
  /**
   *  The attachment in the mail is empty and there is no attachment. map In the key As the attachment ID . value Is the attachment address 
   */
  private Map<String, String> attachments;
  
  
  private String fromAddress;// Sender address 1 a 
  
  private String toAddresses;// Recipient address , It can be used for many, between each address ";" Separation, let's say 450065208@qq.com;lpf@sina.com
  
  private String[] attachFileNames;// The attachment  

  public String getFromAddress() {
    return fromAddress;
  }

  public void setFromAddress(String fromAddress) {
    this.fromAddress = fromAddress;
  }

  public String getToAddresses() {
    return toAddresses;
  }

  public void setToAddresses(String toAddresses) {
    this.toAddresses = toAddresses;
  }

  public String getSubject() {
    return subject;
  }

  public void setSubject(String subject) {
    this.subject = subject;
  }

  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }

  public String[] getAttachFileNames() {
    return attachFileNames;
  }

  public void setAttachFileNames(String[] attachFileNames) {
    this.attachFileNames = attachFileNames;
  }

  public String getEmailHost() {
    return emailHost;
  }

  public void setEmailHost(String emailHost) {
    this.emailHost = emailHost;
  }

  public String getEmailFrom() {
    return emailFrom;
  }

  public void setEmailFrom(String emailFrom) {
    this.emailFrom = emailFrom;
  }

  public String getEmailUserName() {
    return emailUserName;
  }

  public void setEmailUserName(String emailUserName) {
    this.emailUserName = emailUserName;
  }

  public String getEmailPassword() {
    return emailPassword;
  }

  public void setEmailPassword(String emailPassword) {
    this.emailPassword = emailPassword;
  }

  public String getToEmails() {
    return toEmails;
  }

  public void setToEmails(String toEmails) {
    this.toEmails = toEmails;
  }

  public Map<String, String> getPictures() {
    return pictures;
  }

  public void setPictures(Map<String, String> pictures) {
    this.pictures = pictures;
  }

  public Map<String, String> getAttachments() {
    return attachments;
  }

  public void setAttachments(Map<String, String> attachments) {
    this.attachments = attachments;
  }
  
  
}

spring.xml adds configuration information


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd">

  
<!--  Send E-mail  -->
  <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> 
   <property name="host"> 
   <value>${mail.host}</value> 
   </property> 
   <property name="javaMailProperties"> 
      <props> 
       <prop key="mail.smtp.auth">true</prop> 
       <prop key="mail.smtp.timeout">25000</prop> 
      </props> 
   </property>   
   <property name="username"> 
   <value>${mail.username}</value> 
   </property> 
   <property name="password"> 
   <value>${mail.password}</value> 
   </property> 
   <property name="defaultEncoding"> 
   <value>UTF-8</value> 
   </property> 
  </bean> 
  
  <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
    <property name="from" value="${mail.from}" />
    <property name="subject" value="${mail.subject}" />
     <property name="to" value="${mail.to}" />
    <!--
    <property name="text" value=" Email content " />
    -->
  </bean>
</beans>

dev. properties configuration


# email configuration
mail.host=smtp.163.com
mail.username=chenyanqing5945
mail.password=123456

mail.from=chenyanqing5945@163.com# The sender 
mail.to=164792930@qq.com# Recipient (multiple USES , Separated) 
mail.subject=testEmail # The theme 

Related articles: