发送邮件是很常用的功能,注册验证,找回密码,到货通知,欠费提醒等,都可以通过邮件来提醒。
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); } }