发送Html邮件

发送Html邮件

  • 1.本文提供一个java编写的发送邮件工具类。直接新建工具类,复制代码即可。
  • 2.测试信息
  • 3.所需jar包(maven)

1.本文提供一个java编写的发送邮件工具类。直接新建工具类,复制代码即可。

import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;

public class SendMailUtil {

	public static void sendMailUtil(ArrayList<String> to)
			throws GeneralSecurityException, AddressException {

		InternetAddress[] sendTo = new InternetAddress[to.size()];
		for (int i = 0; i < to.size(); i++) {
			sendTo[i] = new InternetAddress(to.get(i));
		}

		// 发件人电子邮箱
		final String from = "[email protected]";
		// 指定发送邮件的主机为 smtp.qq.com
		// String host = "smtp.qq.com"; // QQ 邮件服务器
		String host = "pop.exmail.qq.com"; // 腾讯企业邮箱服务器
		// 获取系统属性
		Properties properties = System.getProperties();
		// 设置邮件服务器
		properties.setProperty("mail.smtp.host", host);
		properties.put("mail.smtp.auth", "true");
		// 关于QQ邮箱,还要设置SSL加密,加上以下代码即可
		MailSSLSocketFactory sf = new MailSSLSocketFactory();
		sf.setTrustAllHosts(true);
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.ssl.socketFactory", sf);
		// 获取默认session对象
		Session session = Session.getDefaultInstance(properties, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				// 发件人邮件用户名、密码
				return new PasswordAuthentication(from, "发件人邮箱密钥"); // 发件人邮箱用户名、密码
			}
		});
		try {
			// 创建默认的 MimeMessage 对象
			MimeMessage message = new MimeMessage(session);
			// Set From: 
			message.setFrom(new InternetAddress(from));
			// Set To: 
			// message.addRecipient(Message.RecipientType.TO, new InternetAddress(tos));
			message.setRecipients(MimeMessage.RecipientType.TO, sendTo);
			// message.addRecipient(Message.RecipientType.CC,new InternetAddress(to));
			// Set Subject: 
			message.setSubject("这个是邮件的主题");
			// 设置消息体
			// message.setText("This is 测试2内容");
			// 发送 HTML 消息, 可以插入html标签
			message.setContent("这里边的内容是html代码",
					"text/html;charset=gb2312");
			// 发送
			Transport.send(message);
		} catch (MessagingException mex) {
			mex.printStackTrace();
		}
	}
}

2.测试信息

@Test 
	 public void name() throws AddressException, GeneralSecurityException {
	 	//配置收件人集合
	 	ArrayList<String> arrayList = new ArrayList<>();
		arrayList.add("[email protected]"); 
		arrayList.add("[email protected]");
	 	SendMailUtil.sendMailUtil(arrayList)
	 }

3.所需jar包(maven)


	javax.mail
	mail
	1.4.7

你可能感兴趣的:(java,邮件)