当前位置: 移动技术网 > IT编程>开发语言>Java > springMVC发送邮件的简单实现

springMVC发送邮件的简单实现

2019年07月22日  | 移动技术网IT编程  | 我要评论

利用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("    附件是个人清单。<br />");
    builder.append("    其中人信息;<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 #主题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网