importjava.util.Properties;
importjavax.mail.Address;
importjavax.mail.MessagingException;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
publicclassSendEmailUtil{
publicstaticbooleansendMail(StringemailAddress,StringemailMsg){
//谁发送(发送方)
Stringfrom=””;
//发给谁
Stringto=emailAddress;
//发送者的用户名和密码(邮箱登录用)
finalStringusername=””;//此处填写发送的邮箱名
finalStringpassword=””;//此处填写登录的邮箱密码
//定义properties对象,设置环境信息
Propertiesproperties=newProperties();
/*
*mail.smtp.host:指定衔接的邮件效劳器的主机名。如:163邮箱就填写smtp.163.com
*若在本地测试的话,需求在本地装置smtp效劳器
*/
properties.setProperty(“mail.smtp.host”,”smtp.163.com”);
//mail.smtp.auth:指定客户端能否要向邮件效劳器提交考证
properties.setProperty(“mail.smtp.auth”,”true”);
/*
*mail.transport.protocol:指定邮件发送协议:smtp。smtp:发邮件;pop3:收邮件
*mail.store.protocol:指定邮件接纳协议
*/
properties.setProperty(“mail.transport.protocol”,”smtp”);
//获取session对象
Sessionsession=Session.getInstance(properties);
//当设置为true,JavaMailAP就会将其运转过程和邮件效劳器的交互命令信息输出到console中,用于JavaMail的调试
session.setDebug(true);
try{
//创立邮件对象
MimeMessagemessage=newMimeMessage(session);
//设置邮件发送方
message.setFrom(newInternetAddress(from));
//设置邮件发送的主题
message.setSubject(“邮件发送设置”);
//设置邮件发送的内容
message.setContent(emailMsg,”text/html;charset=utf-8″);
Transporttransport=session.getTransport();
//衔接邮件效劳器,“”中填写邮件效劳器主机名
transport.connect(“”,25,username,password);
transport.sendMessage(message,newAddress[]{newInternetAddress(to)});
transport.close();
returntrue;
}catch(MessagingExceptione){
e.printStackTrace();
returnfalse;
}
}