最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springMVC發(fā)送郵件的簡單實(shí)現(xiàn)

 更新時間:2017年04月18日 16:34:50   作者:偶遇晨光  
本篇文章主要介紹了springMVC發(fā)送郵件的簡單實(shí)現(xiàn) ,主要是利用利用javax.mail發(fā)送郵件,圖片與附件都可發(fā)送,有興趣的可以了解一下

利用javax.mail發(fā)送郵件,圖片與附件都可發(fā)送

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("-------------執(zhí)行發(fā)送郵件START---------------");
      //寫入excel
      //insuranceService.excelManage();
      //發(fā)郵件
      emailService.emailManage();
    
    logger.info("-------------執(zhí)行發(fā)送郵件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);
    
    //內(nèi)容
    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);
  }



  /**
   * 發(fā)送郵件
   * 
   * @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");
      // 設(shè)置發(fā)件人郵箱
      if (mail.getEmailFrom()!=null) {
        messageHelper.setFrom(mail.getEmailFrom());
      } else {
        messageHelper.setFrom(simpleMailMessage.getFrom());
      }
      
      // 設(shè)置收件人郵箱
      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("請確認(rèn)每張圖片的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("請確認(rèn)每個附件的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());
      // 發(fā)送郵件
      javaMailSender.send(message);
      logger.info("------------發(fā)送郵件完成----------");
      
    } catch (MessagingException e) {
      
      e.printStackTrace();
    }
  }

}

MailModel實(shí)體類

package com.support.entity;

import java.util.Map;

public class MailModel {
  
  /**
   * 發(fā)件人郵箱服務(wù)器
   */
  private String emailHost;
  /**
   * 發(fā)件人郵箱
   */
  private String emailFrom;

  /**
   * 發(fā)件人用戶名
   */
  private String emailUserName;

  /**
   * 發(fā)件人密碼
   */
  private String emailPassword;

  /**
   * 收件人郵箱,多個郵箱以“;”分隔
   */
  private String toEmails;
  /**
   * 郵件主題
   */
  private String subject;
  /**
   * 郵件內(nèi)容
   */
  private String content;
  /**
   * 郵件中的圖片,為空時無圖片。map中的key為圖片ID,value為圖片地址
   */
  private Map<String, String> pictures;
  /**
   * 郵件中的附件,為空時無附件。map中的key為附件ID,value為附件地址
   */
  private Map<String, String> attachments;
  
  
  private String fromAddress;//發(fā)送人地址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">

  
<!-- 發(fā)送郵件 -->
  <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="郵件內(nèi)容" />
    -->
  </bean>
</beans>

 dev.properties配置

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

mail.from=chenyanqing5945@163.com#發(fā)件人
mail.to=164792930@qq.com#收件人(多個用,隔開)
mail.subject=testEmail #主題

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java實(shí)現(xiàn)的xml格式化實(shí)現(xiàn)代碼

    java實(shí)現(xiàn)的xml格式化實(shí)現(xiàn)代碼

    這篇文章主要介紹了java實(shí)現(xiàn)的xml格式化實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2016-11-11
  • Mybatis?如何傳入字符串參數(shù),分割并遍歷

    Mybatis?如何傳入字符串參數(shù),分割并遍歷

    這篇文章主要介紹了Mybatis?如何傳入字符串參數(shù),分割并遍歷,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • Mybatis?SqlSession案例詳解

    Mybatis?SqlSession案例詳解

    這篇文章主要介紹了Mybatis?SqlSession詳解,本文我們講了如何創(chuàng)建SqlSession的幾個步驟,最后我們獲得一個DefaultSqlSession對象,里面包含了執(zhí)行器Executor和配置對象Configuration,需要的朋友可以參考下
    2023-04-04
  • SpringBoot訪問HTML過程詳解

    SpringBoot訪問HTML過程詳解

    這篇文章主要詳細(xì)介紹了SpringBoot訪問HTML的全過程,文章中有詳細(xì)的代碼和圖片講解,感興趣的同學(xué)可以參考一下
    2023-04-04
  • 聊聊springboot2.2.3升級到2.4.0單元測試的區(qū)別

    聊聊springboot2.2.3升級到2.4.0單元測試的區(qū)別

    這篇文章主要介紹了springboot 2.2.3 升級到 2.4.0單元測試的區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java 異步線程監(jiān)聽與結(jié)果回調(diào)及異常捕獲總結(jié)分析

    Java 異步線程監(jiān)聽與結(jié)果回調(diào)及異常捕獲總結(jié)分析

    異常是程序之中導(dǎo)致程序中斷的一種指令流,異常一旦出現(xiàn)并且沒有進(jìn)行合理處理的話,那么程序就將中斷執(zhí)行,這篇文章綜合介紹了異步線程監(jiān)聽與結(jié)果回調(diào)及異常捕獲
    2021-11-11
  • 一文掌握Spring?Boot?日志文件

    一文掌握Spring?Boot?日志文件

    日志是程序的重要組成部分,日志對于我們來說,最主要的用途就是排除和定位問題,這篇文章主要介紹了Spring?Boot?日志文件,需要的朋友可以參考下
    2023-03-03
  • java 矩陣乘法的mapreduce程序?qū)崿F(xiàn)

    java 矩陣乘法的mapreduce程序?qū)崿F(xiàn)

    這篇文章主要介紹了java 矩陣乘法的mapreduce程序?qū)崿F(xiàn)的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • 開發(fā)10年,全記在這本Java進(jìn)階寶典里了

    開發(fā)10年,全記在這本Java進(jìn)階寶典里了

    這篇文章主要給大家分享介紹了這本Java進(jìn)階寶典里,是開發(fā)10年總結(jié)出來的,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧
    2019-04-04
  • SpringBoot使用JSch操作Linux的方法

    SpringBoot使用JSch操作Linux的方法

    JSch是一個Java庫,它提供了SSH(Secure?Shell)的Java實(shí)現(xiàn),允許Java程序通過SSH協(xié)議連接到遠(yuǎn)程系統(tǒng)(如Linux),這篇文章主要介紹了SpringBoot使用JSch操作Linux,需要的朋友可以參考下
    2023-11-11

最新評論

眉山市| 钟祥市| 淮阳县| 姚安县| 隆安县| 临安市| 临湘市| 北宁市| 鲁甸县| 福泉市| 阳西县| 龙口市| 丹阳市| 牡丹江市| 兴义市| 措美县| 玉门市| 宿州市| 广丰县| 双城市| 根河市| 会东县| 自治县| 潼关县| 阆中市| 乌海市| 沐川县| 怀安县| 大田县| 石景山区| 当涂县| 泰宁县| 那曲县| 北票市| 林西县| 定远县| 盐津县| 探索| 县级市| 栾城县| 建水县|