使用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 ...
随机推荐
- PHP读取Mongodb数据报错,Cannot natively represent the long 8331412483000 on this platform
在使用PHP进行读取Mongo数据时,如果读取的int数据过大时,会自动转变为int64位. 并会报以下错误: Cannot natively represent the long 833141248 ...
- poj 1742 Coins (多重背包)
http://poj.org/problem?id=1742 n个硬币,面值分别是A1...An,对应的数量分别是C1....Cn.用这些硬币组合起来能得到多少种面值不超过m的方案. 多重背包,不过这 ...
- 使用 httpkit 来替代 jetty
Compojure 是一个基于 ring 的上层web开发框架.在 lein new compojure my-app 生成的项目中,默认是启用 jetty 服务器的,最近用到了 http-kit 中 ...
- Oracle数据库之四
删除记录的SQL语句 delete from 表名[where 条件];(DML) 注意: 如果没有where子句,代表全部删除(慎用). delete也必须commit后才能生效 truncate也 ...
- Cookie操作类 实现记住用户名和密码的功能
import java.util.Hashtable;import java.util.Iterator;import java.util.Set;import javax.servlet.http. ...
- 【笨嘴拙舌WINDOWS】设备无关图(*.bmp)
设备无关图在windows上面就是一个扩展名为.bmp的文件.我们知道每一种文件都是一个二进制流,只是这个二进制流的开头几个字节是规定了文件的格式..bmp的文件格式如下 “其中信息头是windows ...
- bzoj2428: [HAOI2006]均分数据
模拟退火.挺好理解的.然后res打成了ans一直WA一直WA...!!!一定要注意嗷嗷嗷一定要注意嗷嗷嗷一定要注意嗷嗷嗷. 然后我就一直卡一直卡...发现最少1800次的时候就可以出解了.然后我就去调 ...
- (六)6.15 Neurons Networks Deep Belief Networks
Hintion老爷子在06年的science上的论文里阐述了 RBMs 可以堆叠起来并且通过逐层贪婪的方式来训练,这种网络被称作Deep Belife Networks(DBN),DBN是一种可以学习 ...
- 【Android】SDK工具学习 - Traceview 和 dmtracedump
dmtracedump官方文档 Traceview 根据程序的log,形成图形 dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g out ...
- oracle数据库重建EM
首先直接在文本控制台执行: [emca不像dbca.netca一样会出现图形化的界面,而是通过文本的交互式操作来完成重新配置] emca -config dbcontrol db -repos ...