這篇文章給大家介紹利用springMVC如何實現(xiàn)一個郵件發(fā)送功能,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
成都創(chuàng)新互聯(lián)是專業(yè)的湘陰網(wǎng)站建設(shè)公司,湘陰接單;提供網(wǎng)站設(shè)計、成都做網(wǎng)站,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行湘陰網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊,希望更多企業(yè)前來合作!
利用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("清單"); //附件 Mapattachments = new HashMap (); attachments.put("清單.xlsx",excelPath+"清單.xlsx"); mail.setAttachments(attachments); //內(nèi)容 StringBuilder builder = new StringBuilder(); builder.append("你好!
"); builder.append("    附件是個人清單。
"); builder.append("    其中人信息;
"); builder.append(""); 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(";"); ListtoEmailList = new ArrayList (); 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 > it = mail.getPictures().entrySet() .iterator(); it.hasNext();) { Map.Entry 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 > it = mail.getAttachments() .entrySet().iterator(); it.hasNext();) { Map.Entry 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實體類
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 Mappictures; /** * 郵件中的附件,為空時無附件。map中的key為附件ID,value為附件地址 */ private Map 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 getPictures() { return pictures; } public void setPictures(Map pictures) { this.pictures = pictures; } public Map getAttachments() { return attachments; } public void setAttachments(Map attachments) { this.attachments = attachments; } }
spring.xml添加配置信息
<?xml version="1.0" encoding="UTF-8"?>${mail.host} true 25000 ${mail.username} ${mail.password} UTF-8
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 #主題
關(guān)于利用springMVC如何實現(xiàn)一個郵件發(fā)送功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。