使用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 ...
随机推荐
- file的这几个取得path的方法各有不同,下边说说详细的区别
html, body { font-size: 15px; } body { font-family: Helvetica, "Hiragino Sans GB", 微软雅黑, & ...
- Selenium系列教程(2)
Selenium RC(Selenium远程控制) Selenium RC是一个用Java编写的,允许用户使用无论哪种编程语言对基于Web的应用程序构建测试脚本的工具.Selenium RC克服了Se ...
- ajaxFileUpload插件上传文件 返回 syntaxError :unexpected token
Html 代码<table id="deploy_application" class="bordered-table"> <tr> & ...
- OCJP考试介绍
OCJP考试介绍 考试名称:SCJP / OCJP / 1Z0-851 考试时间:150分钟 考题题目:60道题 通过条件:大于等于61%的题目正确 考点查询:http://www.pearsonvu ...
- 4.0之后的hibernate获取sessionFactory
static{ Configuration config=new Configuration().configure(); ServiceRegistry resgistry = new Servic ...
- BZOJ 1078 斜堆
感谢MATO大神的博客 http://www.cppblog.com/MatoNo1/archive/2013/03/03/192131.html 注意细节. #include<iostream ...
- (四)Logistic Regression
1 线性回归 回归就是对已知公式的未知参数进行估计.线性回归就是对于多维空间中的样本点,用特征的线性组合去拟合空间中点的分布和轨迹,比如已知公式是y=a∗x+b,未知参数是a和b,利用多真实的(x,y ...
- webservices上传文件
客户端: ob_clean(); ob_start(); readfile("D:/44.jpg"); $logo = ob_get_clean(); $pararmArr = a ...
- struts2运行机制
struts2是web应用中一个常用的mvc框架,下面探讨一下其内部运行机制: 1.从客服端浏览器输入的url后,客服端通过http协议发送一个请求到服务器(tomcat),Tomcat收到这个请求之 ...
- php 正则中的"i,m,s,x,e"分别表示什么
i如果设定此修正符,模式中的字符将同时匹配大小写字母.m当设定了此修正符,“行起始”和“行结束”除了匹配整个字符串开头和结束外,还分别匹配其中的换行符的之后和之前.s如果设定了此修正符,模式中的圆点元 ...