背景
使用Java发送邮件,特记录一下代码。
jar包
发送邮件所需三个jar包:additionnal.jar;activation.jar;mail.jar
下载链接,或者自行搜索下载。
实现
package APIRequest;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class AccessToken {
public static void main(String[] args) {
String to = "收件人";
String from = "发件人";
//发送邮件的主机
String host = "邮件服务器地址";
//获得系统属性
Properties properties = System.getProperties();
//设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
//获取默认的session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("邮箱用户名", "邮箱密码"); //发件人邮件用户名、密码
}
});
try {
//创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//消息体,此处可根据实际需求发送HTML信息或者其它附件
message.setSubject("This is a test email!");
message.setText("This is a test email!");
//发送消息
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
个人能力有限,如有谬误欢迎指正!