java mail html_java 发送 mail 纯文本发送和html格式发送

packagetextAnalysis.util;importtextAnalysis.dto.MailInfo;import javax.mail.*;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeBodyPart;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeMultipart;importjava.util.Date;importjava.util.Properties;/*** Created by 草帽boy on 2016/12/8.*/

public classMailSendUtil {private final static String host = "smtp.163.com"; //163的服务器private final static String formName = "YYYXXX@163.com";//你的邮箱private final static String password = "***********"; //授权码private final static String replayAddress = "YYYXXX@163.com"; //你的邮箱public static void sendHtmlMail(MailInfo info)throwsException{

info.setHost(host);

info.setFormName(formName);

info.setFormPassword(password);//网易邮箱的授权码~不一定是密码

info.setReplayAddress(replayAddress);

Message message=getMessage(info);//MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象

Multipart mainPart = newMimeMultipart();//创建一个包含HTML内容的MimeBodyPart

BodyPart html = newMimeBodyPart();//设置HTML内容

html.setContent(info.getContent(), "text/html; charset=utf-8");

mainPart.addBodyPart(html);//将MiniMultipart对象设置为邮件内容

message.setContent(mainPart);

Transport.send(message);

}public static void sendTextMail(MailInfo info) throwsException {

info.setHost(host);

info.setFormName(formName);

info.setFormPassword(password);//网易邮箱的授权码~不一定是密码

info.setReplayAddress(replayAddress);

Message message=getMessage(info);//消息发送的内容

message.setText(info.getContent());

Transport.send(message);

}private static Message getMessage(MailInfo info) throwsException{final Properties p =System.getProperties() ;

p.setProperty("mail.smtp.host", info.getHost());

p.setProperty("mail.smtp.auth", "true");

p.setProperty("mail.smtp.user", info.getFormName());

p.setProperty("mail.smtp.pass", info.getFormPassword());//根据邮件会话属性和密码验证器构造一个发送邮件的session

Session session = Session.getInstance(p, newAuthenticator(){protectedPasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));

}

});

session.setDebug(true);

Message message= newMimeMessage(session);//消息发送的主题

message.setSubject(info.getSubject());//接受消息的人

message.setReplyTo(InternetAddress.parse(info.getReplayAddress()));//消息的发送者

message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"余高峰"));//创建邮件的接收者地址,并设置到邮件消息中

message.setRecipient(Message.RecipientType.TO,newInternetAddress(info.getToAddress()));//消息发送的时间

message.setSentDate(newDate());returnmessage ;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值