admin 管理员组

文章数量: 887016

spring mial 发送邮件

通过spring emial 发送邮件

项目最近需要新增发邮件功能,在网上搜了一些资料,这里整理一下。
java本身提供了发送邮件的API,JavaMail API详细信息可以参照: 《JavaMail API详解》

我用的是spring email,spring email抽象的核心是MailSender接口。spring自带MailSender的实现——JavaMailSenderImpl使用和配置起来都更加简单。

##配置maven

     <dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>4.3.8.RELEASE</version></dependency><dependency><groupId>javax.mail</groupId><artifactId>mail</artifactId><version>1.4.7</version></dependency>

##发送代码

package com.*.*.util;/*** 邮件发送工具类** @author * @create */
@Component
public class EmailUtil {static Logger logger = LoggerFactory.getLogger(EmailUtil.class);/*** 发送邮件** @param mailSend   MailSend* @param mailConfig MailConfig* @throws MessagingException           异常* @throws UnsupportedEncodingException 异常*/public static boolean sendMail(MailSend mailSend, MailConfig mailConfig) {System.out.println("1.send mail send param MailSend is " + mailSend.toString() + "MailConfig is " + mailConfig.toString());//配置邮箱工具参数JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();javaMailSender.setHost(mailConfig.getMailHost());javaMailSender.setPort(mailConfig.getMailPort());javaMailSender.setUsername(mailConfig.getMailUsername());javaMailSender.setPassword(mailConfig.getMailPassword());javaMailSender.setDefaultEncoding("Utf-8");Properties properties = new Properties();properties.setProperty(MailConfig.MAIL_SMTP_TIMEOUT, mailConfig.getMailTimeout());properties.setProperty(MailConfig.MAIL_SMTP_AUTH, "false");javaMailSender.setJavaMailProperties(properties);//设置短信内容MimeMessage mimeMessage = javaMailSender.createMimeMessage();try {// 设置utf-8或GBK编码,否则邮件会有乱码MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");messageHelper.setFrom(mailConfig.getMailUsername(), Utils.notEmpty(mailConfig.getMailFromName()) ? mailConfig.getMailFromName() : mailConfig.getMailUsername());messageHelper.setTo(mailSend.getRecipient());messageHelper.setSubject(mailSend.getSubject());//内容是HTML形式System.out.println("2.send mail start , content is " + mailContent);messageHelper.setText(mailContent, true);//多附件处理if (Utils.notEmpty(mailSend.getAnnex())) {FileSystemResource file = null;for (NoMailAnnex noMailAnnex : mailSend.getAnnex()) {file = new FileSystemResource(noMailAnnex.getAnnexPath());messageHelper.addAttachment(noMailAnnex.getAnnextitle(), file);}}javaMailSender.send(mimeMessage);return true;} catch (Exception e) {System.out.println(("send mail fail!!! mial subject is " + mailSend.getSubject() + e.getMessage()));}return false;}public static void main(String[] args) {//邮箱配置MailConfig mailConfig = new MailConfig();mailConfig.setMailHost("smtp.163");//邮箱服务器mailConfig.setMailPort(25);//端口mailConfig.setMailTimeout();//超时,这里我设置默认25000mailConfig.setMailUsername("********@163");//用户名,mailConfig.setMailPassword("*******");//密码mailConfig.setMailFromName("***");//发件人,不填默认用发件邮箱//邮件内容MailSend mailSend = new MailSend();mailSend.setSubject("五一出行天气");//主题//内容mailSend.setText("<p>由于项目中引入了多个数据源,并且需要对多个数据源进行写操作,那么多数据源的事务管理自然成了不可避免的问题,这也让我对@Transactional注解有了进一步的理解(但实际上也并不是非常深入)然而这是一个演进的过程,刚开始项目中并没有使用@Transactional指定具体的TransactionManager,所以新增一个数据源后,对原有的事务产生了影响了,这也是偶尔在一次测试报错而结果没有回滚之后才发现的,遂对于@Transactional注解的一些参数项进行了了解。。</p>");mailSend.setRecipient("***@qq");//收件人邮箱try {//邮件发送,如果收件人邮箱错误,邮件被退回。是不会抛异常的EmailUtil.sendMail(mailSend, mailConfig);} catch (Exception e) {System.out.println(e.getMessage());}}
}

##MailSend

package com.*.*.model;/*** 邮件发送实体类* @author * @create * */public class MailSend {/*** 收件人*/private String recipient;/*** 邮件主题*/private String subject;/*** 邮件内容*/private String text;/*** 邮件附件路径*/private List<NoMailAnnex> annex;public String getRecipient() {return recipient;}public void setRecipient(String recipient) {this.recipient = recipient;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getText() {return text;}public void setText(String text) {this.text = text;}public List<NoMailAnnex> getAnnex() {return annex;}public void setAnnex(List<NoMailAnnex> annex) {this.annex = annex;}

##MailConfig

package com.*.*.model;/*** 邮件发送配置* @author * @create */public class MailConfig {public static final String MAIL_SMTP_TIMEOUT = "mail.smtp.timeout";public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";/*** 服务器*/private String mailHost;/*** #端口号*/private Integer mailPort;/*** #邮箱账号*/private String mailUsername;/*** #邮箱授权码*/private String mailPassword;/*** #时间延迟*/private String mailTimeout ;/*** #发送人邮箱* --废弃字段,默认用mailUsername字段*/private String mailFrom;/*** #发送人署名*/private String mailFromName;public String getMailFromName() {return mailFromName;}public void setMailFromName(String mailFromName) {this.mailFromName = mailFromName;}public String getMailHost() {return mailHost;}public void setMailHost(String mailHost) {this.mailHost = mailHost;}public Integer getMailPort() {return mailPort;}public void setMailPort(Integer mailPort) {this.mailPort = mailPort;}public String getMailUsername() {return mailUsername;}public void setMailUsername(String mailUsername) {this.mailUsername = mailUsername;}public String getMailPassword() {return mailPassword;}public void setMailPassword(String mailPassword) {this.mailPassword = mailPassword;}public String getMailTimeout() {return mailTimeout;}public void setMailTimeout() {this.mailTimeout = "25000";}public String getMailFrom() {return mailFrom;}public void setMailFrom(String mailFrom) {this.mailFrom = mailFrom;}
}

##NoMailAnnex

package com.*.*.model;/*** 说明: 附件* 创建人:* 创建时间:* @version*/
public class NoMailAnnex{/*** 标题*/private String annextitle;/*** 文件真实路径*/private String annexPath;public String getAnnexPath() {return annexPath;}public void setAnnexPath(String annexPath) {this.annexPath = annexPath;}public String getAnnextitle() {return annextitle;}public void setAnnextitle(String annextitle) {this.annextitle = annextitle;}   
}

##关于邮件中发送网络资源图片被拦截

  • 测试时,发送到QQ邮箱的时候会发现图片找不到。这是因为QQ邮箱会默认拦截陌生邮件中的图片。

  • 邮件中内嵌图片

 /*** 这部分的代码未测试*/MimeMessage message = mailSender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom("testFrom@163");helper.setTo("testTo@qq");helper.setSubject("Spring Email Test");helper.setText("<html><body><img src='cid:testLogo'>"+ "<h4>Hello World!!!</h4>"+ "</body></html>", true);//第二个参数表明这是一个HTML//src='cid:testLogo'表明在消息中会有一部分是图片并以testLogo来进行标识ClassPathResource image = new ClassPathResource("logo.jpg");System.out.println(image.exists());helper.addInline("testLogo", image);//添加内联图片,第一个参数表明内联图片的标识符,第二个参数是图片的资源引用mailSender.send(message);

##参考博客

  • ** 《Spring学习笔记之使用Spring发送Email》**
  • ** 《JavaMail API详解》**

本文标签: spring mial 发送邮件