前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java发送邮件带url、html

java发送邮件带url、html

作者头像
全栈程序员站长
发布2022-08-28 10:23:16
1.3K0
发布2022-08-28 10:23:16
举报
文章被收录于专栏:全栈程序员必看

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

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

创建一个密码验证器类

代码语言:javascript
复制
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);
	}
}

邮箱实体类:

代码语言:javascript
复制
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;
	} 
}

邮件发送类:

代码语言:javascript
复制
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,测试发送:

代码语言:javascript
复制
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
java发送邮件带url、html

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

demo下载地址

欢迎大家指正讨论。

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档