JavaMail发送邮件第一版
首先,我们先来了解一个基本的知识点,用什么工具来发邮件?
简单的说一下,目前用的比较多的客户端:OutLook,Foxmail等
顺便了解一下POP3、SMTP协议的区别:
POP3,全名为“Post Office Protocol - Version 3”,即“邮局协议版本3”。是TCP/IP协议族中的一员,由RFC1939 定义。本协议主要用于支持使用客户端远程管理在服务器上的电子邮件,提供了SSL加密。
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。SMTP协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。
POP服务器是用来收信的,而且每个Email地址一般只有一个。如果你要同时收取多个邮箱的信件,就必须挨个设置每个邮箱的POP3服务器地址。
SMTP则是负责邮件服务器与邮件服务器之间的寄信的通讯协定。
pop3的端口:110 smtp的端口:25
下面就是真实的例子了。
JAVA邮件发送的步骤:
1、构建一个继承自javax.mail.Authenticator的具体类,并重写里面的getPasswordAuthentication()方法。此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利。
2、构建一个properties文件,该文件中存放SMTP服务器地址等参数。
3、通过构建的properties文件和javax.mail.Authenticator具体类来创建一个javax.mail.Session。Session的创建,就相当于登录邮箱一样。剩下的自然就是新建邮件。
4、构建邮件内容,一般是javax.mail.internet.MimeMessage对象,并指定发送人,收信人,主题,内容等等。
5、使用javax.mail.Transport工具类发送邮件。
示例1:使用JavaMail发送邮件——文本文件
EmailAuthenticator类
public class EmailAuthenticator extends Authenticator {
private String username; //用户名
private String userpass;//密码
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @return the userpass
*/
public String getUserpass() {
return userpass;
}
public void setUsername(String username) {
this.username = username;
}
public void setUserpass(String userpass) {
this.userpass = userpass;
}
/**
*
*/
public EmailAuthenticator() {
}
/**
*
* @param username
* @param userpass
*/
public EmailAuthenticator(String username, String userpass) {
this.username = username;
this.userpass = userpass;
}
/**
*
*/
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,userpass);
}
}
Mail类
public class Mail {
private String mailServer,from,to,mailSubject,mailContent;
private String username,password;
public Mail() {
//认证登录用户
username="wgy@mail.com";
//username="m15010033XXX_1@163.com";
//认证密码
password="wgy";
//password="greatXXX";
//认证的邮箱对应的邮件服务器
// mailServer="192.168.15.XXX";
mailServer="mail.com";
//发件人信息
from="wgy@mail.com";
//from="m15010033XXX_1@163.com";
//收件人信息
to="dog@mail.com";
//to="tom";
//to="yyXXX@126.com";
//邮件标题
mailSubject="心跳";
//邮件内容
mailContent="XXX——————————————————————————————未知的时间和地点";
}
//设置邮件服务器
@SuppressWarnings("static-access")
public void sendInfo() {
Properties props=System.getProperties();
//指定邮件server
props.put("mail.smtp.host", mailServer);
//是否开启认证
props.put("mail.smtp.auth", "true");
//smtp协议的
props.put(");
//产生Session服务
EmailAuthenticator authenticator=new EmailAuthenticator(username, password);
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session session = Session.getInstance(props, authenticator);
// 根据session创建一个邮件消息
Message message=new MimeMessage(session);
try {
// 创建邮件发送者地址
message.setFrom(new InternetAddress(from));
// Message.RecipientType.TO属性表示接收者的类型为TO
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置邮件消息的主题
message.setSubject(mailSubject);
//设置内容(设置字符集处理乱码问题) ,设置HTML内容
message.setContent(mailContent,"text/html;charset=gbk");
// 设置邮件消息发送的时间
message.setSentDate(new Date());
//创建Transport实例
Transport tran=session.getTransport("smtp");
//发送邮件
tran.send(message,message.getAllRecipients());
tran.close();
} catch (Exception e) {
e.getMessage();
}
}
Test类
public static void main(String[] args) {
Mail mail=new Mail();//实例化
mail.sendInfo();
System.out.println("OK");
}
}
这样就可以实现了服务器之间的传输。
示例:使用Spring发送简单、带附件、HTML邮件
MailWithHTML类
public class MailWithHTML {
private JavaMailSender mailSender; //必须使用 JavaMailSender
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void send() throws MessagingException,IOException{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("wgy@mail.com");
helper.setTo("tom");
helper.setSubject("欢迎来到员工社区");
StringBuffer sb = new StringBuffer();
sb.append("<html><head>");
sb.append("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\">");
sb.append("<head><body>");
sb.append("<font color='blue' size='5' face='Arial'>");
sb.append("尊敬的jerry您好:</font><br/><br/>");
sb.append(" ");
sb.append("<font color='black' size='4' face='Arial'>");
sb.append("恭喜您在员工社区注册账号成功!请妥善保管您的账号," +
"如果登录时忘记密码,可以在网站登录页找回。<br/>");
sb.append("<br/><br/>系统管理员</font>");
//增加内嵌图片设置
// sb.append("<br/><img src=\"cid:photo\"></img>");
sb.append("</body></html>");
helper.setText(sb.toString(),true);
//增加内嵌文件
ClassPathResource file = new ClassPathResource("/cn/bdqn/attachfiles/Quartz.rar");
helper.addInline("photo", file);
mailSender.send(mimeMessage);
}
MailWithAttachment类
public class MailWithAttachment {
private JavaMailSender mailSender; //必须使用 JavaMailSender
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void send() throws MessagingException,IOException{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("wgy@mail.com");
//helper.setFrom("m15010033582_1@163.com");
helper.setTo("tom");
helper.setSubject("问好");
helper.setText("好久不见,最近好吗?");
//添加附件1
ClassPathResource file1 = new ClassPathResource(
"/cn/bdqn/attachfiles/test.doc");
helper.addAttachment(file1.getFilename(), file1.getFile());
//添加附件2:附件的文件名为中文时,需要对文件名进行编码转换,解决乱码问题
ClassPathResource file2 = new ClassPathResource(
"/cn/bdqn/attachfiles/JAVA-SSH(三大框架)面试题.doc");
helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile());
mailSender.send(mimeMessage);
}
Mail类
public class Mail {
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void send(){
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("wgy@mail.com");
message.setTo("tom");
message.setSubject("问好");
message.setText("好久不见!!!!!!!!!");
mailSender.send(message);
}
}
applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="192.168.15.2xx"></property><!-- 服务器 -->
<!-- <property name="host" value="smtp.163.com"></property> --><!-- 服务器 -->
<property name="></property><!-- 端口 -->
<property name="username" value="wgy"></property><!-- 用户名 -->
<!-- <property name="username" value="m15010033xxx_1@163.com"></property> -->
<property name="password" value="wgy"></property><!-- 密码 -->
<!-- <property name="password" value="greatxxx"></property> -->
<property name="protocol" value="smtp" ></property><!-- 协议 -->
<property name="defaultEncoding" value="utf-8"></property><!-- 默认编码 -->
<property name="javaMailProperties">
<props>
<!-- 设置SMTP服务器需要用户验证 -->
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="mail" class="cn.bdqn.Mail">
<property name="mailSender" ref="mailSender"></property>
</bean>
<bean id="mailWithAttachment" class="cn.bdqn.MailWithAttachment">
<property name="mailSender" ref="mailSender"></property>
</bean>
<bean id="mailWithHtml" class="cn.bdqn.MailWithHTML">
<property name="mailSender" ref="mailSender"></property>
</bean>
</beans>
MailTest类
public class MailTest {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
/*测试简单邮件*/
Mail mail = (Mail)context.getBean("mail");
mail.send();
/*测试带附件的邮件*/
try{
MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment");
mailWithAttach.send();
}catch(Exception e){
System.out.print(e.toString());
}
/*测试HTML格式的邮件*/
try{
MailWithHTML mailWithHtml = (MailWithHTML)context.getBean("mailWithHtml");
mailWithHtml.send();
System.out.println("我ok了");
}catch(Exception e){
System.out.print(e.toString());
}
}
注意
jar包
资源
示例:使用模板创建邮件正文
MailService类
public class MailService {
private JavaMailSender mailSender;
private Configuration freeMarkerConfiguration;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void setFreeMarkerConfiguration(Configuration freeMarkerConfiguration) {
this.freeMarkerConfiguration = freeMarkerConfiguration;
}
private String getMailText(){
String htmlText = "";
try{
//获取模板实例
Template template = freeMarkerConfiguration.getTemplate("mail.ftl");
//通过Map传递动态数据
Map map = new HashMap();
map.put("user", "jerry");
//解析模板文件
htmlText = FreeMarkerTemplateUtils
.processTemplateIntoString(template, map);
}catch(IOException e){
e.printStackTrace();
}catch(TemplateException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return htmlText;
}
public void sendMail() throws MessagingException,IOException{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(
mimeMessage, true, "UTF-8");
helper.setFrom("tina@mail.com");
helper.setTo("jerry@mail.com");
helper.setSubject("欢迎来到员工社区");
helper.setText(getMailText(),true);
mailSender.send(mimeMessage);
}
applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.com"></property>
<property name="></property>
<property name="username" value="tina"></property>
<property name="></property>
<property name="protocol" value="smtp" ></property>
<property name="defaultEncoding" value="utf-8"></property>
<property name="javaMailProperties">
<props>
<!-- 设置SMTP服务器需要用户验证 -->
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="freeMarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<!-- 指定模板文件路径 -->
<property name="templateLoaderPath" value="cn/bdqn/mailtemplate/"></property>
<!-- 设置FreeMarker环境变量 -->
<property name="freemarkerSettings">
<props>
<prop key=</prop>
</props>
</property>
</bean>
<bean id="mailService" class="cn.bdqn.MailService">
<property name="mailSender" ref="mailSender"></property>
<property name="freeMarkerConfiguration" ref="freeMarkerConfiguration"></property>
</bean>
</beans>
MailTest类
public class MailTest {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
try{
MailService mailService = (MailService)context.getBean("mailService");
mailService.sendMail();
}catch(Exception e){
System.out.print(e.toString());
}
}
注意:
jar包
资源
到这里就完成了。。。。。。。。。
JavaMail发送邮件第一版的更多相关文章
- JavaMail发送邮件
发送邮件包含的内容有: from字段 --用于指明发件人 to字段 --用于指明收件人 subject字段 --用于说明邮件主题 cc字段 -- 抄送,将邮件发送给收件人的同时抄 ...
- web应用中使用JavaMail发送邮件
现在很多的网站都提供有用户注册功能, 通常我们注册成功之后就会收到一封来自注册网站的邮件.邮件里面的内容可能包含了我们的注册的用户名和密码以及一个激活账户的超链接等信息.今天我们也来实现一个这样的功能 ...
- JavaMail发送邮件的笔记及Demo
最近碰到一个需求,就是注册用户时候需要向用户发送激活邮箱,于是照着网上搜来的demo自己试着运行了一下,发件时我用的是网易163邮箱,收件时用QQ邮箱,运行后报了一个错误: 网络上搜索解决方式,多次尝 ...
- web应用中使用JavaMail发送邮件 。。转载
现在很多的网站都提供有用户注册功能, 通常我们注册成功之后就会收到一封来自注册网站的邮件.邮件里面的内容可能包含了我们的注册的用户名和密码以及一个激活账户的超链接等信息.今天我们也来实现一个这样的功能 ...
- (转载)JavaWeb学习总结(五十三)——Web应用中使用JavaMail发送邮件
博客源地址:http://www.cnblogs.com/xdp-gacl/p/4220190.html 现在很多的网站都提供有用户注册功能, 通常我们注册成功之后就会收到一封来自注册网站的邮件.邮件 ...
- JavaWeb学习总结(五十三)——Web应用中使用JavaMail发送邮件
现在很多的网站都提供有用户注册功能, 通常我们注册成功之后就会收到一封来自注册网站的邮件.邮件里面的内容可能包含了我们的注册的用户名和密码以及一个激活账户的超链接等信息.今天我们也来实现一个这样的功能 ...
- javamail发送邮件的简单实例
今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题.为了以后使用方便,自己写了段代码,打成jar包,以方便以后使用.呵呵 以下三段代码是我的全部代码,朋友们如果想用,直接 ...
- javamail发送邮件的简单实例(转)
今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题.为了以后使用方便,自己写了段代码,打成jar包,以方便以后使用.呵呵 注意:要先导入javamail的mail.jar ...
- javamail发送邮件的简单实例(转)
javamail发送邮件的简单实例 今天学习了一下JavaMail,javamail发送邮件确实是一个比较麻烦的问题.为了以后使用方便,自己写了段代码,打成jar包,以方便以后使用.呵呵 以下三段代码 ...
随机推荐
- postgresql无法安装pldbgapi的问题
要对函数进行调试需要安装插件pldbgapi,当初在windows上面的postgresql实例中执行了一下语句就安装上了: create extension pldbgapi; 但是在linux中执 ...
- 《CPU的工作过程》
本文转载自inter官方网址:https://software.intel.com/zh-cn/articles/book-Processor-Architecture_CPU_work_proces ...
- C#执行异步操作的几种方式比较和总结
C#执行异步操作的几种方式比较和总结 0x00 引言 之前写程序的时候在遇到一些比较花时间的操作例如HTTP请求时,总是会new一个Thread处理.对XxxxxAsync()之类的方法也没去了解过, ...
- 如何利用 Visual Studio 自定义项目或工程模板
在开发项目的时候,由其是商业性质的大型项目时,往往需要在每个代码文件上都加上一段关于版权.开发人员的信息,并且名称空间上都需要带有公司的标志.这个时候,是选择在开发的时候手动添加还是自动生成呢? 我们 ...
- Entity Framework 6 Recipes 2nd Edition(11-1)译 -> 从“模型定义”函数返回一个标量值
第11章函数 函数提供了一个有力代码复用机制, 并且让你的代码保持简洁和易懂. 它们同样也是EF运行时能利用的数据库层代码.函数有几类: Rowset Functions, 聚合函数, Ranking ...
- JSON.stringify()与JSON.parse()
JSON.stringify()用于把一个对象解析成字符串,如 var student = { age: 23, name: 'wang' } JSON.stringify(student); 结果: ...
- Android 浏览器 —— 使用 WebView 实现文件下载
对当前的WebView设置下载监听 mCurrentWebView.setDownloadListener(new DownloadListener() { @Override public void ...
- 计算机人物系列-Mauchly,Eckert,Goldstine
关键词:莫尔学院(Moore School),阿伯丁试验场(Aberdeen Proving Ground), 雷明顿兰德公司(Remington Rand Corporation), IBM院士(I ...
- 今天有群友不是很清楚htm直接存数据库的危害,我简单举个例子
通过这个案例就知道为什么不要把原生的html放数据库了 常见的几种转码 常用的几种显示方法 只有原生html和最下面一种弹框了,变成了持久xss 如果是Ajax的方式,请用@Ajax.JavaS ...
- 前端学PHP之PDO预处理语句
× 目录 [1]定义 [2]准备语句 [3]绑定参数[4]执行查询[5]获取数据[6]大数据对象 前面的话 本来要把预处理语句和前面的基础操作写成一篇的.但是,由于博客园的限制,可能是因为长度超出,保 ...



