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)
上一篇 2022年5月14日 下午11:40
下一篇 2022年5月14日 下午11:40


相关推荐

  • gradle搭建springboot_gradle和maven的区别

    gradle搭建springboot_gradle和maven的区别以下是我以一个刚入行职场菜鸡的个人见解,不喜勿碰。自我感觉java入门很是简单,网上的各种教程满天飞,但是需要深刻的认识到java的具体的思想就比较需要去花费功夫了。那么这就需要我们看spring的源码了。那问什么要看spring源码呢?下面我引用别人的写的博客。https://blog.csdn.net/cjm812752853/article/details/76222491/接下来讲如何将s…

    2022年8月12日
    14
  • 成员变量,类变量,局部变量的区别是什么_内部变量和局部变量

    成员变量,类变量,局部变量的区别是什么_内部变量和局部变量面向对象编程1.封装性面向对象编程核心思想之一就是将数据和对数据的操作封装在一起,通过抽象即从具体的实例中抽取共同的性质形成一般的概念。2.继承子类可以继承父类的属性和功能,即子类继承了父类所有的数据和数据上的操作,同时又可以添加子类独有的数据和数据上的操作。3.多态有两种意义的多态    1)操作名称的多态  2)和继承有关的多态类:

    2025年7月26日
    5
  • python最新激活码2021 4月底【在线注册码/序列号/破解码】

    python最新激活码2021 4月底【在线注册码/序列号/破解码】,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月18日
    52
  • 搜索中的深度匹配模型

    搜索中的深度匹配模型文章作者 辛俊波腾讯高级研究员编辑整理 HohXil 内容来源 作者授权出品平台 DataFunTalk 注 欢迎转载 转载请在留言区留言 导读 在上

    2026年3月16日
    2
  • JavaScript中的document.cookie的使用

    JavaScript中的document.cookie的使用 我们已经知道,在document对象中有一个cookie属性。但是Cookie又是什么?“某些Web站点在您的硬盘上用很小的文本文件存储了一些信息,这些文件就称为Cookie。”——MSIE帮助。一般来说,Cookies是CGI或类似,比HTML高级的文件、程序等创建的,但是javascript也提供了对Cookies的很全面的访问权利。  我们先要学

    2022年7月27日
    9
  • 批处理文件for循环_windows批处理文件怎么打开

    批处理文件for循环_windows批处理文件怎么打开windows批处理for循环用法

    2022年10月12日
    7

发表回复

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

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