前文:最近学习了利用java发送邮件相关知识,怕忘记,所以笔记之。
一:在Maven环境下,pom配置 jar包依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
二:需要发送邮件的端口,服务,邮件及账户和密码
首先要有配置文件,命名为mail.properties,放在classpath路径下
email.host=xxxx //邮件服务器主机host,目前只支持SMTP协议(163或qq) 网易默认是:smtp.163.com
email.port=25 //端口号
email.from=发送者的邮件账户
username=发送者的邮件账户的用户名
password=发送者的邮件账户的密码
三:操作类
public class EmailHelper {
private static final ResourceBundle bundle = ResourceBundle.getBundle("mail");
private static final String sendFrom = bundle.getString("email.from");
private static final String username = bundle.getString("username");
private static final String password = bundle.getString("password");
private static final String host = bundle.getString("email.host");
public static void sendEmail(String someone, String subject, String content){
Properties props = new Properties();
props.setProperty("mail.host", host);
props.setProperty("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator(){
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
session.setDebug(true);
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(sendFrom));
message.setRecipients(RecipientType.TO,InternetAddress.parse(someone));
//message.setRecipients(RecipientType.TO,InternetAddress.parse("测试的接收的邮件多个以逗号隔开"));
try {
message.setSubject(subject);
message.setContent(content,"text/html;charset=UTF-8");
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
四:测试方法
@Test
public void tsetemail(){
String content ="Hello,This is a test email!!!!";
//参数分别为接收者邮箱、title、内容body
EmailHelper.sendEmail("imhuangw@163.com", "标题", content);
}