您的位置:首页 > 编程语言 > Java开发

java发送邮件带url、html

2016-04-26 23:43 465 查看
代码也是在网上扒的,自己用到了也整理了下方便以后再用。

创建一个密码验证器类

package com.mail.test;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAuthenticator extends Authenticator {

public MailAuthenticator(String userName,String userPwd){
this.userAccout = userName;
this.userPassword = userPwd;
}

private String userAccout;
private String userPassword;
public String getUserAccout() {
return userAccout;
}
public void setUserAccout(String userAccout) {
this.userAccout = userAccout;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}

@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(userAccout, userPassword);
}
}


邮箱实体类:

package com.mail.test;

import java.util.Properties;

public class MainInfo {
// 发送邮件的服务器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 邮件发送者的地址
private String fromAddress;
// 邮件接收者的地址
private String toAddress;
// 登陆邮件发送服务器的用户名和密码
private String userName;
private String password;
// 是否需要身份验证
private boolean validate = false;
// 邮件主题
private String subject;
// 邮件的文本内容
private String content;
// 邮件附件的文件名
private String[] attachFileNames;
/**
* 获得邮件会话属性
*/
public Properties getProperties(){
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] attachFileNames) {
this.attachFileNames = attachFileNames;
}
}


邮件发送类:

package com.mail.test;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {

/**
*
* @title sendMailText
* @description  发送纯文本形式邮件
* @date 2016-4-26 下午11:13:06
* @param mainInfo
* @return boolean
*/
public boolean sendMailText(MainInfo mainInfo) {
Properties props = mainInfo.getProperties();
MailAuthenticator mailauthenticator = null;
if (mainInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
mailauthenticator = new MailAuthenticator(mainInfo.getFromAddress(),
mainInfo.getPassword());
}
Session sendMailSession = Session.getDefaultInstance(props,
mailauthenticator);
Message sendMailMessage = new MimeMessage(sendMailSession);
try {
Address from = new InternetAddress(mainInfo.getFromAddress());
sendMailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mainInfo.getToAddress());
sendMailMessage.setRecipient(Message.RecipientType.TO, to);
// 设置邮件消息的主题
sendMailMessage.setSubject(mainInfo.getSubject());
// 设置邮件消息发送的时间
sendMailMessage.setSentDate(new Date());
// 设置邮件消息的主要内容
sendMailMessage.setText(mainInfo.getContent());
// 发送邮件
Transport.send(sendMailMessage);
return true;
} catch (AddressException e) {
// TODO Auto-generated catch block
System.out.println("邮件地址有误。。");
e.printStackTrace();
return false;
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}

/**
*
* @title sendMailHtml
* @description  发送带有html的邮件
* @date 2016-4-26 下午11:13:26
* @param mainInfo
* @return boolean
*/
public boolean sendMailHtml(MainInfo mainInfo) {
Properties props = mainInfo.getProperties();
MailAuthenticator mailauthenticator = null;
if (mainInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
mailauthenticator = new MailAuthenticator(mainInfo.getFromAddress(),
mainInfo.getPassword());
}
Session sendMailSession = Session.getDefaultInstance(props,
mailauthenticator);
Message sendMailMessage = new MimeMessage(sendMailSession);
try {
Address from = new InternetAddress(mainInfo.getFromAddress());
sendMailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mainInfo.getToAddress());
sendMailMessage.setRecipient(Message.RecipientType.TO, to);

// 设置邮件消息的主题
sendMailMessage.setSubject(mainInfo.getSubject());
// 设置邮件消息发送的时间
sendMailMessage.setSentDate(new Date());

// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(mainInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
sendMailMessage.setContent(mainPart);
// 发送邮件
Transport.send(sendMailMessage);
return true;
} catch (AddressException e) {
System.out.println("邮件地址有误。。");
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
}
}


组织发送内容,包含url、html,测试发送:

package com.mail.test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class MailTest {

public static void main(String[] args) {
try {
MailSender sender  = new MailSender();
MainInfo mainInfo = new MainInfo();
mainInfo.setMailServerHost("smtp.163.com");  //imap.exmail.qq.com
mainInfo.setMailServerPort("25");
mainInfo.setUserName("烦烦烦");
mainInfo.setFromAddress("*******");
mainInfo.setPassword("*******");
mainInfo.setToAddress("*******");
mainInfo.setSubject("测试内容标题");
StringBuffer url = new StringBuffer();
url.append("http://locahost:8080");
url.append("noa");
url.append("/reportFindPassword/updatePassword.action?");
url.append("employeeCode=123456");
url.append("&employeeName="+URLEncoder.encode("发送邮件测试", "UTF-8"));
url.append("&pemployeeCode=123456");
url.append("&pemployeeName="+URLEncoder.encode("哈哈", "UTF-8"));
url.append("&email=*******@***.com");
url.append("&dateTime=20160418162538");
StringBuffer content = new StringBuffer();
content.append("<div><div style='margin-left:4%;'>");
content.append("<p style='color:red;'>");
content.append("啊啊啊(123456)您好:</p>");
content.append("<p style='text-indent: 2em;'>您正在使用密码找回功能,请点击下面的链接完成密码找回。</p>");
content.append("<p style='text-indent: 2em;display: block;word-break: break-all;'>");
content.append("链接地址:<a style='text-decoration: none;' href='"+url.toString()+"'>"+url.toString()+"</a></p>");
content.append("</div>");
content.append("<ul style='color: rgb(169, 169, 189);font-size: 18px;'>");
content.append("<li>为了保障您帐号的安全,该链接有效期为12小时。</li>");
content.append("<li>该链接只能使用一次,请周知。</li>");
content.append("<li>如果该链接无法点击,请直接复制以上网址到浏览器地址栏中访问。</li>");
content.append("<li>请您妥善保管,此邮件无需回复。</li>");
content.append("</ul>");
content.append("</div>");
mainInfo.setContent(content.toString());
mainInfo.setValidate(true);
sender.sendMailHtml(mainInfo);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

}


其中链接中包含的中文做URL转码,

最后的邮件为:



此类邮件URL需要做校验,如果链接中只包含一个标示,则只对当前标示加密,如果所有参数都暴露在地址栏中可以将所有参数拼起来用MD5或者其他方式加密后存放在该URL中,例如为validateCode,此次也要对validateCode的值做encode转换,不然特殊符号在URL中会自动转换,之后只对validateCode校验即可知道该链接是否正确。

demo下载地址

欢迎大家指正讨论。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: