项目准备:javax.mail-1.5.4.jar
一个邮箱此处以@163邮箱为例子
(设置如图1.2)
代码如下:
public static void sendMail(MailMsgBean mail, String project_name, YN_FLAG flag) {
logger.info("邮件发送-------->>to:[{}]“,mail.getTarget_mail());
//发送人
final String from = mail.getHost_mail().trim();
//发送协议类型:此处用的是smtf
String host = mail.getHost_type().trim();
//授权密码
final String pwd = mail.getHost_pwd().trim();
//邮件内容
String msg = mail.getContent_mail();
//收件人
String to = mail.getTarget_mail();
//激活协议
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
try {
// QQ邮箱特殊处理
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pwd);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("邮件主题");
//String body = new String(content.getBytes("iso-8859-1"),"utf-8");
String msg = "<html><head></head><body>" +content+"</body></html>"
//此处以发送html形式为例(可以以纯文本发送)
message.setContent(msg, "text/html;charset=gb2312");
//发送
if(!Assert.isEmpty(to)){
Transport.send(message);
}
logger.info("邮件发送完成!");
} catch (Exception e) {
e.printStackTrace();
logger.info("邮件发送error!");
}
}