使用JavaMail API发送邮件
发送邮件是很常用的功能,注册验证,找回密码,到货通知,欠费提醒等,都可以通过邮件来提醒。
Java中发送邮件需要使用javax.mail.jar包,读者可以上网搜索或去官方下载,下载地址为:
下面贴上发送邮件的核心代码。
// Get system properties
Properties properties = System.getProperties(); // Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true"); // create email authenticator.
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}; // Get the default Session object.
Session session = Session.getDefaultInstance(properties, authenticator); try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session); // Set From: header field of the header.
message.setFrom(new InternetAddress(from)); // Set To: header field of the header.
for (String to : toList) {
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
} // Set Subject: header field
message.setSubject("这是邮件标题", "utf-8");
// Send the complete message parts
message.setContent("这里是邮件内容", "text/html;charset=utf-8"); // Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace(); }
我自己定义了一个类EmailSender,这个类提供了邮件群发功能,以及在邮件中发送附件。用户继承这个类,重载getSubject,getContent和getAttachments这三个方法便可以发送邮件。
类定义如下:
package com.iot.common.email; import java.io.File; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Multipart; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeBodyPart; import javax.mail.BodyPart; import javax.mail.PasswordAuthentication; import javax.mail.Authenticator; import java.util.ArrayList; import javax.mail.MessagingException; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.Session; import java.util.Properties; import java.util.List; /**
* 邮件发送类,用来发送邮件给用户.<br />
*
* @author Sam
*
*/
public abstract class EmailSender extends Authenticator { private String host;
private String port;
private String username;
private String password;
private String from; public EmailSender() {
this.host = PropertiesUtil.getProperty(Constant.EMAIL_HOST);
this.port = PropertiesUtil.getProperty(Constant.EMAIL_HOST_PORT);
this.username = PropertiesUtil.getProperty(Constant.EMAIL_USER_NAME);
this.password = PropertiesUtil.getProperty(Constant.EMAIL_PASSWORD);
this.from = PropertiesUtil.getProperty(Constant.EMAIL_SENDER);
} /**
* EmailSender构造函数,需要用户提供host,port,username,password,from等信息。<br />
*
* @param host
* ,smtp服务器地址
* @param port
* ,smtp服务器端口
* @param username
* ,邮箱用户名
* @param password
* ,邮箱密码
* @param from
* ,邮箱发送人
*/
public EmailSender(String host, String port, String username,
String password, String from) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
this.from = from;
} /**
* 发送邮件到指定用户
*
* @param to
* , 邮件发送对象
* @return ture 发送成功, false发送失败
*/
public Boolean send(String to) { List<String> toList = new ArrayList<>();
toList.add(to); return send(toList);
} /**
* 群发邮件
*
* @param toList
* ,需要接受邮件的用户
* @return ture 发送成功, false发送失败
*/
public Boolean send(List<String> toList) { // Get system properties
Properties properties = System.getProperties(); // Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true"); // create email authenticator.
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}; // Get the default Session object.
Session session = Session.getDefaultInstance(properties, authenticator); try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session); // Set From: header field of the header.
message.setFrom(new InternetAddress(from)); // Set To: header field of the header.
for (String to : toList) {
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
} // Set Subject: header field
message.setSubject(getSubject(), "utf-8"); // Create the message part
BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message
messageBodyPart.setContent(getContent(), "text/html;charset=utf-8"); // Create a multipar message
Multipart multipart = new MimeMultipart(); // Set text message part
multipart.addBodyPart(messageBodyPart); // add attachment
List<File> attchments = getAttachments();
if (attchments != null && attchments.size() > 0) {
for (File attachment : attchments) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachment.getName());
multipart.addBodyPart(messageBodyPart);
}
} // Send the complete message parts
message.setContent(multipart); // Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace(); return false;
} return true;
} /**
* 获取邮件主题,支持html格式。
*
* @return
*/
protected abstract String getSubject(); /**
* 获取邮件内容,支持html格式。
*
* @return
*/
protected abstract String getContent(); /**
* 获取附件列表,若不需要发送附件,请返回null或长度为0的List<File>列表.<br />
*
* @return
*/
protected abstract List<File> getAttachments(); }
与邮件发送服务器相关信息存储在properties.xml文件中,文件结构如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>邮件系统配置文件</comment> <entry key="EMAIL_HOST">smtp.126.com</entry> <entry key="EMAIL_HOST_PORT">25</entry> <entry key="EMAIL_USER_NAME"><username>@126.com</entry> <entry key="EMAIL_PASSWORD"><password></entry> <entry key="EMAIL_SENDER"><username>@126.com</entry>
</properties>
PropertiesUtil类用于读取properties.xml文件中的属性,代码如下:
/**
*
*/
package com.iot.common.email; import java.io.IOException;
import java.io.InputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties; /**
* @author Sam <br />
* 读取properties信息 <br />
*
*/
public class PropertiesUtil { /**
* Get property by name
*
* @param name
* @return
*/
public static String getProperty(String name) {
return properties.getProperty(name);
} private static Properties properties; /****
* Initialize properties
*/
static {
String filePath = "properties.xml";
InputStream stream = PropertiesUtil.class.getClassLoader()
.getResourceAsStream(filePath); properties = new Properties(); try {
properties.loadFromXML(stream);
} catch (InvalidPropertiesFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
静态常量类Contanst代码如下:
package com.iot.common.email; /**
*
* @author Lynn
*
* Store all constant field
*
*/
public class Constant { /* email sending information */
public static final String EMAIL_HOST = "EMAIL_HOST";
public static final String EMAIL_HOST_PORT = "EMAIL_HOST_PORT";
public static final String EMAIL_USER_NAME = "EMAIL_USER_NAME";
public static final String EMAIL_PASSWORD = "EMAIL_PASSWORD";
public static final String EMAIL_SENDER = "EMAIL_SENDER"; }
测试代码如下:
package com.iot.common.email; import java.io.File; import java.util.ArrayList; import java.util.List; public class EmailTest { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub EmailSender sender = new EmailSender() { @Override
protected String getSubject() {
// TODO Auto-generated method stub
return "测试邮件,请不要回复";
} @Override
protected String getContent() {
// TODO Auto-generated method stub
return "<h1>尊敬的用户:</h1><br /><p>这是一封测试邮件,请不要恢复改邮件!</p>";
} @Override
protected List<File> getAttachments() {
// TODO Auto-generated method stub List<File> files=new ArrayList<>();
files.add(new File("d:/district.txt"));
files.add(new File("d:/test2.jar")); return files;
}
}; List<String> to = new ArrayList<>();
to.add("409253645@qq.com");
to.add("sam@steperp.com");
to.add("hui@126.com"); sender.send(to); } }
使用JavaMail API发送邮件的更多相关文章
- JavaMail应用--通过javamail API实现在代码中发送邮件功能
JavaMail应用 在日常开发中,可能会引用到发邮件功能,例如在持续集成中,自动化测试运行完毕,自动将测试结果以报表的形式发送邮件给相关人.那么在Java中如何实现发邮件呢? 在java EE ...
- JavaMail API 详细分解
在使用Spring框架的过程中,它的优势之一就是在于跟其他一些技术的整合,如JavaMail .任务调度.缓存策略等技术.今天就Java Mail详细阐述.JavaMail API是被设计为与协议无关 ...
- javamail模拟邮箱功能发送电子邮件-基础实战篇(javamail API电子邮件实例)
引言: JavaMail 是一种可选的.能用于读取.编写和发送电子消息的包 JavaMail jar包下载地址:http://java.sun.com/products/javamail/downlo ...
- javamail模拟邮箱功能发送电子邮件-中级实战篇【新增附件发送方法】(javamail API电子邮件实例)
引言: JavaMail jar包下载地址:http://java.sun.com/products/javamail/downloads/index.html 此篇是紧随上篇文章而封装出来的,阅读本 ...
- JavaMail API 1.4.7邮件发送
下载oracle javaMail API: http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive- ...
- JavaMail API
JavaMail API的核心类:会话.消息.地址.验证程序.传输,存储和文件夹.所有这些类都可以在JavaMail API即javax.mail的顶层包中找到,尽管你将频繁地发现你自己使用的子类是在 ...
- javamail模拟邮箱功能--邮件回复-中级实战篇【邮件回复方法】(javamail API电子邮件实例)
引言: JavaMai下载地址l jar包:http://java.sun.com/products/javamail/downloads/index.html 此篇是紧随上篇文章而封装出来的,阅读本 ...
- javamail模拟邮箱功能获取邮件内容-中级实战篇【内容|附件下载方法】(javamail API电子邮件实例)
引言: JavaMail jar包下载地址:http://java.sun.com/products/javamail/downloads/index.html 此篇是紧随上篇文章而封装出来的,阅读本 ...
- JavaMail API的应用
JavaMail API 是一个用于阅读.编写和发送电子消息的可选包(标准扩展),用来创建邮件用户代理(Mail User Agent,MUA)类型程序. JavaMail API 需要 JavaBe ...
随机推荐
- zabbix接口调用注意事项--Python
不知道该怎么写,但是明显得写点什么,担心时间长了,忘记,再回顾时又要重新摸索一遍 一.Request:post params: 1. 第一层的参数处理: 第一层的参数设置为变量 2. 其他层参数格式不 ...
- R语言数据类型转换
test for data type is.numeric(), is.character(), is.vector(), is.matrix(), is.data.frame() convert i ...
- 无法创建链接服务器 "(null)" 的 OLE DB 访问接口 "Microsoft.Ace.OLEDB.12.0" 的实例。
--开启导入功能 exec sp_configure 'show advanced options',1 reconfigure exec sp_configure 'Ad Hoc ...
- leetcode:Excel Sheet Column Number
Given a column title as appear in an Excel sheet, return its corresponding column number. For exampl ...
- 使用@RequestParam绑定请求参数到方法参数
@RequestParam注解用于在控制器中绑定请求参数到方法参数.用法如下:@RequestMapping public void advancedSearch( @RequestParam(& ...
- 51nod1421 最大MOD值
O(n2)tle.O(nlognlogn) #include<cstdio> #include<cstring> #include<cctype> #include ...
- Core Text
Core Text 本文所涉及的代码你可以在这里下载到 https://github.com/kejinlu/CTTest,包含两个项目,一个Mac的NSTextView的测试项目,一个iOS的Cor ...
- 所在实习公司的JS笔试题
在班上无聊的时候看到了一份JS笔试题(我是电面进去的,没做过这份题~~),开始还觉得蛮简单......后来觉得还是很有意思的,贴出来一起看看. 题目一: if(!("a" in w ...
- 【转】DB2 常用命令
1. 打开命令行窗口 #db2cmd 2. 打开控制中心 # db2cmd db2cc 3. 打开命令编辑器 db2cmd db2ce =====操作数据库命令===== 4. 启动数据库实例 ...
- C++ 编写Windows service
最近实现一个windows server端守护进程启动服务功能(c++实现),遇到了一些问题,记录一下 1. 启动Service实现代码: int _tmain(int argc, TCHAR* ar ...