java發送郵件帶url、html

創建一個密碼驗證器類

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校驗即可知道該鏈接是否正確。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章