当前位置: 首页 > 编程笔记 >

springMVC发送邮件的简单实现

牟华翰
2023-03-14
本文向大家介绍springMVC发送邮件的简单实现,包括了springMVC发送邮件的简单实现的使用技巧和注意事项,需要的朋友参考一下

利用javax.mail发送邮件,图片与附件都可发送

1,Controller类

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("-------------执行发送邮件START---------------");
      //写入excel
      //insuranceService.excelManage();
      //发邮件
      emailService.emailManage();
    
    logger.info("-------------执行发送邮件END---------------");
    
  }

}

2,service类

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();
    //主题
    mail.setSubject("清单"); 
    
    //附件
    Map<String, String> attachments = new HashMap<String, String>();
    attachments.put("清单.xlsx",excelPath+"清单.xlsx");
    mail.setAttachments(attachments);
    
    //内容
    StringBuilder builder = new StringBuilder();
    builder.append("<html><body>你好!<br />");
    builder.append("&nbsp&nbsp&nbsp&nbsp附件是个人清单。<br />");
    builder.append("&nbsp&nbsp&nbsp&nbsp其中人信息;<br />");
    builder.append("</body></html>");
    String content = builder.toString();
    
    mail.setContent(content);
    
    sendEmail(mail);
  }



  /**
   * 发送邮件
   * 
   * @author chenyq
   * @date 2016-5-9 上午11:18:21
   * @throws Exception
   */
  @Override
  public void sendEmail(MailModel mail) {
    // 建立邮件消息
    MimeMessage message = javaMailSender.createMimeMessage();
    
    MimeMessageHelper messageHelper;
    try {
      messageHelper = new MimeMessageHelper(message, true, "UTF-8");
      // 设置发件人邮箱
      if (mail.getEmailFrom()!=null) {
        messageHelper.setFrom(mail.getEmailFrom());
      } else {
        messageHelper.setFrom(simpleMailMessage.getFrom());
      }
      
      // 设置收件人邮箱
      if (mail.getToEmails()!=null) {
        String[] toEmailArray = mail.getToEmails().split(";");
        List<String> toEmailList = new ArrayList<String>();
        if (null == toEmailArray || toEmailArray.length <= 0) {
          throw new SimpleException("收件人邮箱不得为空!");
        } else {
          for (String s : toEmailArray) {
            if (s!=null&&!s.equals("")) {
              toEmailList.add(s);
            }
          }
          if (null == toEmailList || toEmailList.size() <= 0) {
            throw new SimpleException("收件人邮箱不得为空!");
          } 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());
      }
      
      // 邮件主题
      if (mail.getSubject()!=null) {
        messageHelper.setSubject(mail.getSubject());
      } else {
        
        messageHelper.setSubject(simpleMailMessage.getSubject());
      }
      
      // true 表示启动HTML格式的邮件
      messageHelper.setText(mail.getContent(), true);
      
      // 添加图片
      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("请确认每张图片的ID和图片地址是否齐全!");
          }
          
          File file = new File(filePath);
          if (!file.exists()) {
            throw new RuntimeException("图片" + filePath + "不存在!");
          }
          
          FileSystemResource img = new FileSystemResource(file);
          messageHelper.addInline(cid, img);
        }
      }
      
      // 添加附件
      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("请确认每个附件的ID和地址是否齐全!");
          }
          
          File file = new File(filePath);
          if (!file.exists()) {
            throw new RuntimeException("附件" + filePath + "不存在!");
          }
          
          FileSystemResource fileResource = new FileSystemResource(file);
          messageHelper.addAttachment(cid, fileResource);
        }
      }
      messageHelper.setSentDate(new Date());
      // 发送邮件
      javaMailSender.send(message);
      logger.info("------------发送邮件完成----------");
      
    } catch (MessagingException e) {
      
      e.printStackTrace();
    }
  }

}

MailModel实体类

package com.support.entity;

import java.util.Map;

public class MailModel {
  
  /**
   * 发件人邮箱服务器
   */
  private String emailHost;
  /**
   * 发件人邮箱
   */
  private String emailFrom;

  /**
   * 发件人用户名
   */
  private String emailUserName;

  /**
   * 发件人密码
   */
  private String emailPassword;

  /**
   * 收件人邮箱,多个邮箱以“;”分隔
   */
  private String toEmails;
  /**
   * 邮件主题
   */
  private String subject;
  /**
   * 邮件内容
   */
  private String content;
  /**
   * 邮件中的图片,为空时无图片。map中的key为图片ID,value为图片地址
   */
  private Map<String, String> pictures;
  /**
   * 邮件中的附件,为空时无附件。map中的key为附件ID,value为附件地址
   */
  private Map<String, String> attachments;
  
  
  private String fromAddress;//发送人地址1个
  
  private String toAddresses;//接收人地址,可以为很多个,每个地址之间用";"分隔,比方说450065208@qq.com;lpf@sina.com
  
  private String[] attachFileNames;//附件 

  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添加配置信息

<?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">

  
<!-- 发送邮件 -->
  <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="邮件内容" />
    -->
  </bean>
</beans>

 dev.properties配置

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

mail.from=chenyanqing5945@163.com#发件人
mail.to=164792930@qq.com#收件人(多个用,隔开)
mail.subject=testEmail #主题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小牛知识库。

 类似资料:
  • 本文向大家介绍Java实现简单邮件发送,包括了Java实现简单邮件发送的使用技巧和注意事项,需要的朋友参考一下 JAVA MAIL是利用现有的邮件账户发送邮件的工具,比如说,我在网易注册一个邮箱账户,通过JAVA Mail的操控,我可以不亲自登录网易邮箱,让程序自动的使用网易邮箱发送邮件。这一机制被广泛的用在注册激活和垃圾邮件的发送等方面。 Java邮件发送的大致过程是这样的: 1、构建一个继承自

  • 本文向大家介绍php简单实现发送带附件的邮件,包括了php简单实现发送带附件的邮件的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了php简单实现发送带附件的邮件。分享给大家供大家参考。具体如下: 下面是静态html代码: sendmail.php文件代码: 希望本文所述对大家的php程序设计有所帮助。

  • 本文向大家介绍Python实现的简单发送邮件脚本分享,包括了Python实现的简单发送邮件脚本分享的使用技巧和注意事项,需要的朋友参考一下 近来有些东西需要监控报警发邮件,然后在网上找了点材料,自己写了一个简单发送邮件的脚本,主要就是运用python的smtplib模块,分享给大家看一下:

  • 以下是发送简单电子邮件的示例。 在这里,我们使用了JangoSMPT服务器,通过该服务器将电子邮件发送到我们的目标电子邮件地址。 环境设置章节中介绍了该设置 。 发送简单的电子邮件步骤如下: 参加一个会议 创建一个默认的MimeMessage对象,并在消息中设置From, To, Subject 。 将实际消息设置为: message.setText("your text goes here");

  • 本文向大家介绍Java Mail邮件发送如何实现简单封装,包括了Java Mail邮件发送如何实现简单封装的使用技巧和注意事项,需要的朋友参考一下 首先每次发送需要配置的东西很多,包括发件人的邮箱和密码、smtp服务器和SMTP端口号等信息。其次,没有将发送和邮件内容相分离。按照单一职责原则,应该有且仅有一个原因引起类的变更[1]。最后一个问题是,我们的代码不仅自己用,也很可能让别人调用。别人调用

  • 本文向大家介绍java邮件发送的实现,包括了java邮件发送的实现的使用技巧和注意事项,需要的朋友参考一下 邮件是在日常生活中,这篇文章主要介绍了java实现基于SMTP发送邮件的方法,实例分析了java基于SMTP服务发送邮件的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下. 1.写一个 MailSendProper 类封装需要的属性 2、写一个  EmailMessage 封装 发送信息