通过java发送邮件_【开发笔记】- 发送邮件(通过JavaMail发送)

importjava.io.UnsupportedEncodingException;importjava.security.GeneralSecurityException;importjava.util.Properties;importjavax.mail.Authenticator;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.PasswordAuthentication;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;importorg.apache.log4j.Logger;importcom.juihai.entity.EmailTO;public classSendEmailUtils {/**日志输出*/

private static Logger log = Logger.getLogger(SendEmailUtils.class);public static boolean send(EmailTO to) throwsGeneralSecurityException{final String user =to.getSender();final String password =to.getPassword();

log.info("SendEmailUtils >>>> Start Send Mail");

Properties properties= System.getProperties();//获取系统属性

properties.setProperty("mail.smtp.host", to.getHost());//设置邮件服务器 "smtp.163.com",这是发件人的邮箱服务器

properties.put("mail.smtp.auth", "true");

String senderNick= null;

//部分邮箱服务器需要开启SSL验证才可以发送邮件,需要的话,开启注释即可/*MailSSLSocketFactory sf = new MailSSLSocketFactory();// SSL验证 begin

sf.setTrustAllHosts(true);

properties.put("mail.smtp.ssl.enable", "true");

properties.put("mail.smtp.ssl.socketFactory", sf);// SSL验证 end*/Session session=Session.getDefaultInstance(properties,newAuthenticator() {publicPasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(user, password); //发件人邮件用户名、密码

}

});try{

MimeMessage message= new MimeMessage(session);//创建默认的 MimeMessage对象

senderNick = javax.mail.internet.MimeUtility.encodeText("Juihai");//设置发件人昵称

message.setFrom(new InternetAddress(senderNick+""));//message.addRecipient(Message.RecipientType.TO,new InternetAddress());//创建单个收件人

String[] tos = to.getToAdress();//创建多个收件人

if (tos != null && tos.length != 0) {

InternetAddress[] toAddress= newInternetAddress[tos.length];for (int i = 0; i < tos.length; i++) {

toAddress[i]= newInternetAddress(tos[i]);

}

message.setRecipients(Message.RecipientType.TO, toAddress);

}

message.setSubject(to.getTitle());//设置邮件主题//message.setText(content);//发送纯文本内容

message.setContent(to.getContent(), "text/html;charset=utf-8");//发送html邮件内容

Transport.send(message);//发送Email

log.info(" SendEmailUtils邮件发送成功");return true;

}catch(MessagingException mex) {

mex.printStackTrace();

log.info(" >>>>SendEmailUtils邮件发送失败"+mex);

}catch(UnsupportedEncodingException e) {

log.info(" >>>>SendEmailUtils邮件发送失败-设置发件人昵称error"+e);

e.printStackTrace();

}return false;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值