前言
邮箱在工作使用比较多,大家都比较熟悉。如果有未来做开发需求要做邮箱通知的,淡定,看过来。本篇博客教大家如何发送邮件,因为发邮件是免费的,而短信通知是需要费用的。成本可想而知。
准备工作
编辑器:eclipse,
QQ邮箱账号一套
实战
因为这次我们是把这个发送邮件加在我已有的项目中,但是配置的过程是有的。
首先我们把发送邮件的配置文件在Java Web项目的src目录创建好,当然是创建xml文件。
然后编写里面的代码
源码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<!-- 去QQ官网查出来的 -->
<property name="host" value="smtp.qq.com" />
<property name="port" value="587" />
<!-- 发送邮件的邮箱号 -->
<property name="username" value="这里请填写发送邮件的邮箱号" />
<!-- 授权码,注意这里不是邮箱号的密码哦 -->
<property name="password" value="请填写当前邮箱号的授权码" />
<property name="protocol" value="smtp" />
<property name="defaultEncoding" value="utf-8" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
</beans>
获得授权码:首先先进入邮箱,然后点击“设置”,再然后点击“账户”,然后往下拉动页面找到对应的服务,开起“POP3/SMTP服务”
点击开启服务的同时会弹出这个框,这个框的意思是让你用你QQ密保的手机号码发送内容“配置邮件客户端”到“1069070069”。一定要密保手机发送的哦,发送完成就点击“我已发送”。
点完“我已发送”之后不出意外就显示授权码,然后我们就复制放到配置文件对应的位置。
接下来我们要去编写发送邮箱的工具类,编写直接调用就OK啦。
现在我的工具类包新建一个类,我的类名叫“EmailUtil”。
源码
package com.bdqn.it.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component("emailutil")
public class EmailUtil {
@Autowired
private JavaMailSender sender;
/**
*
* @param to接收人
* @param title邮件标头
* @param content邮件内容
*/
public void sendMsg(String to, String title, String content){
SimpleMailMessage smm = new SimpleMailMessage();
smm.setFrom("请填写你的邮箱号");
smm.setTo(to);
smm.setSubject(title);
smm.setText(content);
sender.send(smm);
System.out.println("发送邮件成功!");
}
}
然后在我们的方法中调用这个发送邮件的方法。
因为我的项目中是充值账户发送邮箱通知的,接下来我充值一个看看结果。
成功了!赶快去试试吧!如有不足请多多指教。