java发送邮件带url、html

java发送邮件带url、htmljava发送邮件,内容包含URL、HTML,并且对URL中文编码,URL的有效性校验。

大家好,又见面了,我是你们的朋友全栈君。

代码也是在网上扒的,自己用到了也整理了下方便以后再用。

创建一个密码验证器类

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转码,

最后的邮件为:

java发送邮件带url、html

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

demo下载地址

欢迎大家指正讨论。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/146533.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 通信网络基础pdf_通信网络系统基础

    通信网络基础pdf_通信网络系统基础目录TCP通信概述服务端架构客户端架构应用层协议客户端连接服务端(错误示范)UDP通信概述程序结构通信数据处理TCP通信概述TCP通信双方在进行数据交换之前,先要建立连接,连接建立后,通信双方之间相当于有一条隧道,数据按顺序在该隧道中传输,数据传输完毕后,双方可以选择关闭隧道,连接结束。TCP通信编程中,“请求方”主动连接“被请求方”,该过…

    2022年9月21日
    0
  • Java实现判断闰年

    Java实现判断闰年Java实现闰年判断需求分析:年份如果满足以下两个条件中的其中一个则可将其年份判断位闰年一、能被4整除,但不能被100整除,就是闰年;二、能被400整除,也是闰年;需求实现方案一:使用if的嵌套实现packagecom.qingsu.basis;importjava.util.Scanner;publicclassProcessControl{ publicstaticvoidmain(String[]args){ //判断闰年 //1.能被4整除

    2022年7月17日
    15
  • Wlan与WiFi[通俗易懂]

    Wlan与WiFi[通俗易懂]首先我们简单介绍下WLAN无线上网,其全称是:Wireless Local Area Networks,中文解释为:无线局域网络,是一种利用射频(Radio Frequency RF)技术进行据传输的系统,该技术的出现绝不是用来取代有线局域网络,而是用来弥补有线局域网络之不足,以达到网络延伸之目的,使得无线局域网络能利用 简单的存取架构让用户透过它,实现无网线、无距离限制的通畅网络。WLAN 使用

    2022年7月11日
    16
  • 词向量算法「建议收藏」

    词向量算法「建议收藏」https://www.cnblogs.com/the-wolf-sky/articles/10192363.htmlhttps://blog.csdn.net/weixin_37947156/article/details/83146141基于神经网络的表示一般称为词向量、词嵌入(wordembdding)或分布式表示。神经网络的词向量和其他分布式类似,都基于分布式表达方式,核心依然是上…

    2022年6月11日
    33
  • 为什么说中国必须建设本土存储产业

    为什么说中国必须建设本土存储产业

    2022年3月5日
    38
  • 时滞模型的matlab编程_adams多体动力学仿真视频

    时滞模型的matlab编程_adams多体动力学仿真视频Matlab仿真含时滞多智体一致性分析,附代码系统结构如下图所示:clear;clc;%2014_多智能体网络的一致性问题研究_纪良浩%此为Paper中的示例代码%例2.1:A=[0,0,0.1,0,0;0.1,0,0,0,0;0,0.15,0,0,0;0,0.25,0,0,0;0.2,0,0,0,0;];D=[0,0,0,0,0;

    2022年10月1日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号