java发送邮件,带跳转链接地址(包含遇见的坑)

本文介绍了如何使用Java发送带有HTML和跳转链接的邮件,并分享了遇到的@value无法读取配置文件的bug及解决方法。通过创建密码验证器、邮箱实体和邮件发送类,实现了邮件发送功能。在实际操作中,发现URL必须至少分两次拼接才能确保跳转有效。同时,提供了读取配置文件的工具类,以实现灵活配置发件人信息。

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();
		}
	}
 
}

最后效果图:
在这里插入图片描述



下面是我修改后的版本:
修改版:工具类(我只需要,发送带超链接的邮件)

package com.hjfit.gym.common.util;

import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;

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

public class MailUtil {
/**
	 * 发送Html链接的email
	 * @param mainInfo
	 * @return
	 */
	public static 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;
		}
	}
}

修改版:(部分代码,主要部分),算是serviceImpl调用部分

		public SchoolResponse sendReportEmail(Long wxId,Long schoolId,String email){
					MainInfo mainInfo = new MainInfo();		//邮件基础设置
					mainInfo.setMailServerHost(PropertiesUtil.getValue("email.mailServerHost", ""));  	//imap.exmail.qq.com
					mainInfo.setMailServerPort(PropertiesUtil.getValue("email.MailServerPort", ""));
					mainInfo.setUserName(PropertiesUtil.getValue("email.userName", ""));				//发件人  名字
					mainInfo.setFromAddress(PropertiesUtil.getValue("email.fromAddress", ""));				//发邮人  账号
					mainInfo.setPassword(PropertiesUtil.getValue("email.password", ""));				//密码
					mainInfo.setSubject(PropertiesUtil.getValue("email.subject", ""));				//主题
					mainInfo.setToAddress(email);														//收件人
//					System.out.println("访问路径:----"+PropertiesUtil.getValue("email.textpath", "")+rname+".zip");
					StringBuffer url = new StringBuffer();						//邮件内容
					url.append(PropertiesUtil.getValue("email.textpath", ""));	//地址
					url.append(rname+".zip");									//名称
					StringBuffer content = new StringBuffer();					//邮件文本内容
					content.append("<div><div style='margin-left:4%;'>");
					content.append("<h3>学校管理员,您好:</h3>");
					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='color:red;text-decoration: none;' href='"+url.toString()+"'>点我一键下载</a></p>");
					content.append("</div>");
					content.append("<ul style='color: rgb(169, 169, 189);font-size: 18px;'>");
//					content.append("<li>为了保障链接正常使用,请您尽快下载,该链接有效期为24小时。</li>");
					content.append("<li>如果该链接无法点击,请直接复制以上网址到浏览器地址栏中访问。</li>");
					content.append("<li>请您妥善保管,此邮件无需回复。</li>");
					content.append("</ul></div>");
					mainInfo.setContent(content.toString());
					mainInfo.setValidate(true);
					MailUtil.sendMailHtml(mainInfo);
					}

我这里还用到了,算是工具类,读取配置文件
因为,我遇到一个@value 读取不到配置文件的bug。主要是还没解决
所以写了个读取配置文件工具类,这里使用配置文件的方式,主要是灵活配置,发件人信息。

package com.fitness.wx.member.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;

/**
 * 读取配置properties文件工具类
 * .properties文件放到自己的项目的context ClassLoader的可以加载的目录下
 * @author zhouwf
 *
 */
public class PropertiesUtil {

	public static Properties properties = new Properties();
	private static URI uri;

	public static String getValue(String key, String value) {
		if(properties.getProperty(key)==null){
			return value;
		}else{
			return properties.getProperty(key);
		}
	}

	/**
	 * 更改配置文件(内存中)
	 * @param key
	 * @param value
	 */
	public static void updateProperties(String key, String value) {
		properties.setProperty(key, value);
	}

	public static void loadFile(String file){
		try {
			properties.load(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(file));
			 uri = Thread.currentThread().getContextClassLoader().getResource(file).toURI(); 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @描述	 : 将属性值写入配置文件中
	 * @作者	 : SHGU
	 * @param key
	 * @param value
	 */
	public static void writePropertiesFile(String file,String key, String value) {
		try {
			OutputStream fos = new FileOutputStream(new File(uri));  
			properties.setProperty(key, value);
            // 以适合使用 load 方法加载到 Properties 表中的格式,   
            // 将此 Properties 表中的属性列表(键和元素对)写入输出流   
			properties.store(fos, "Update '" + key + ":"+value);  
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

其他,应该就没什么了,说一下我用这个遇到的bug,这里截图说明一下吧
在这里插入图片描述
url应该是跳转地址,但是使用过程中,如果不分两次拼接,则不会跳转。可以多拼接几次,但是最少是两次。
你们使用的时候注意一下。(url.append(str) )
希望能帮助到你们!!!!!!!!!!!!!!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值