激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - springMVC發送郵件的簡單實現

springMVC發送郵件的簡單實現

2020-09-13 12:19偶遇晨光 Java教程

本篇文章主要介紹了springMVC發送郵件的簡單實現 ,主要是利用利用javax.mail發送郵件,圖片與附件都可發送,有興趣的可以了解一下

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

1,Controller類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
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實體類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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;//接收人地址,可以為很多個,每個地址之間用";"分隔,比方說[email protected];[email protected]
  
  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添加配置信息

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?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配置

?
1
2
3
4
5
6
7
8
# email configuration
mail.host=smtp.163.com
mail.username=chenyanqing5945
mail.password=123456
 
[email protected]#收件人(多個用,隔開)
mail.subject=testEmail #主題

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://www.cnblogs.com/chenyq/p/5512134.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 在线男人天堂 | 国产伦久视频免费观看视频 | 斗罗破苍穹在线观看免费完整观看 | 国产精品久久久久久久久久三级 | 久久影院一区二区三区 | 欧美激情 在线播放 | 素人视频在线观看免费 | 毛片在线免费播放 | 免费一级在线视频 | 成人福利视频导航 | 久久久一区二区精品 | 国产婷婷一区二区三区 | 毛片视频大全 | 狠很操| 欧美一区二区三区久久精品视 | 人人看人人舔 | 韩国十九禁高潮床戏在线观看 | 免费毛片在线 | 毛片在哪里看 | 日韩av成人 | 欧美aaaaaaaa | 成人爱情偷拍视频在线观看 | 91网站链接| 久久免费激情视频 | 精品中文字幕视频 | 日韩一级片黄色 | 91精品观看91久久久久久国产 | 国产羞羞视频在线观看 | 国产视频在线播放 | 日韩视频在线观看免费视频 | 色柚视频网站ww色 | 久久国产综合精品 | 成人在线精品视频 | 男女一边摸一边做羞羞视频免费 | www.av520| 国产精品免费久久久久 | 黄色一级毛片免费看 | 亚洲精品aa | 国产精品一区在线观看 | 国产成人在线观看免费 | 日韩欧美高清一区 |