说在前面
这几天有点乱七八糟,前几天实现了ping++的微信支付,后来觉得免费版的ping++有点坑,一个月只提供1000次api调用(我们自己做测试都用去了差不多200次),而基础版一年999的只提供5000次,所以果断弃坑(这里有点对不起金亦冶大哥),选择原生的微信支付,今天顺便搞定了邮件发送,现在要说的就是如何使用JavaMail实现邮件发送,这么晚了就长话短说了,直接进入!
问题描述
由于自己实现了微信支付总觉得安全性不够高,所以打算加个邮件报警功能,如果用户采用了非法操作就直接发邮件提醒我们几个项目的管理人员。
要添加的maven依赖:
<!-- 邮件 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.8</version>
</dependency>
在resources中增加一个spring-mail.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
default-autowire="byName">
<!-- 实现邮件服务 -->
<bean id="mimeMessage" class="javax.mail.internet.MimeMessage"
factory-bean="javaMailSender" factory-method="createMimeMessage" />
<bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.qq.com" />
<property name="username" value="xxxx@qq.com" />
<!-- //你的邮箱 -->
<property name="password" value="yyyy" />
<!-- //邮箱密码 -->
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.host">smtp.qq.com</prop>
<prop key="mail.smtp.timeout">25000</prop>
<prop key="mail.smtp.port">25</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.fallback">false</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
</props>
</property>
</bean>
<bean id="mailService" class="ssm.aidai.serviceImpl.MailServiceImpl">
<property name="mailSender" ref="javaMailSender" />
<property name="mimeMessage" ref="mimeMessage" />
</bean>
</beans>
在web.xml中引入对spring-mail.xml文件的扫描
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 更多的是bean文件的配置 -->
<param-value>classpath:conf/spring-mail.xml</param-value>
</context-param>
提供service接口
package ssm.aidai.service;
import ssm.aidai.pojo.MailModel;
public interface MailService {
public void sendAttachMail(MailModel mail);
}
提供实现类
package ssm.aidai.serviceImpl;
import java.io.File;
import java.util.Date;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import ssm.aidai.pojo.MailModel;
import ssm.aidai.service.MailService;
public class MailServiceImpl implements MailService {
private JavaMailSender mailSender;
private MimeMessage mimeMessage;
private static Logger logger = Logger.getLogger(MailServiceImpl.class);
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void setMimeMessage(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}
/**
* 发送html格式的,带附件的邮件
*/
@Override
public void sendAttachMail(MailModel mail) {
try {
MimeMessageHelper mailMessage = new MimeMessageHelper(
this.mimeMessage, true, "UTF-8");
mailMessage.setFrom(mail.getFromAddress());// 设置邮件消息的发送者
mailMessage.setSubject(mail.getSubject());// 设置邮件消息的主题
mailMessage.setSentDate(new Date());// 设置邮件消息发送的时间
mailMessage.setText(mail.getContent(), true); // 设置邮件正文,true表示以html的格式发送
String[] toAddresses = mail.getToAddresses().split(";");// 得到要发送的地址数组
for (int i = 0; i < toAddresses.length; i++) {
mailMessage.setTo(toAddresses[i]);
for (String fileName : mail.getAttachFileNames()) {
mailMessage.addAttachment(fileName, new File(fileName));
}
// 发送邮件
this.mailSender.send(this.mimeMessage);
logger.info("send mail ok=" + toAddresses[i]);
}
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}
}
最后提供测试,直接访问传参即可
/**
* @author:稀饭
* @time:2017年3月6日 下午7:40:42
* @filename:TestDemo.java
*/
package ssm.aidai.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import ssm.aidai.pojo.MailModel;
import ssm.aidai.service.MailService;
import com.sun.istack.logging.Logger;
@Controller
@RequestMapping("/testController")
public class TestDemo {
Logger logger = Logger.getLogger(TestDemo.class);
@Autowired
private MailService mailService;
@RequestMapping(value = "/send")
@ResponseBody
public void sendEmail(HttpServletRequest request) {
MailModel mm = new MailModel();
//附件
String fileNames[] = { "G:/profession/Java/project/aidai/src/main/resources/conf/spring.xml" };
mm.setAttachFileNames(fileNames);
mm.setFromAddress("xxx@qq.com");
mm.setToAddresses("yyy@qq.com;");
mm.setContent("这是来自xx的一封信,如果你收到了,证明xxx的邮件功能搞定了!");
mm.setSubject("xx测试(来自稀饭的一封信)");
mailService.sendAttachMail(mm);
}
}
这里要提及几个点:
使用的时候如果出现了Authentication failed; nested exception is javax.mail.AuthenticationFailedException这个bug,可以考虑以下两个地方入手解决:
- 1、开启POP3/SMTP服务,具体步骤看图:
开启后会获取一个密码,而这个密码正式spring-mail.xml中的配置密码,切记!
- 2、发件人必须是你在spring-mail.xml中填写的邮箱。
**ps: 如果有demo源码需求可以考虑私聊我! **
Note:发布的这些文章全都是自己边学边总结的,难免有纰漏,如果发现有不足的地方,希望可以指出来,一起学习咯,么么哒。
开源爱好者,相信开源的力量必将改变世界:
** osc :** https://git.oschina.net/xi_fan
github: https://github.com/wiatingpub