javax.mail 发送

幸阳波
2023-12-01

依赖

<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>mail</artifactId>
	<version>1.4.1</version>
</dependency>
  

代码

package com.likeyichu;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

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

public class TestMail {
	public static void sendMail(String user, String password,
			String toMail, String mailTitle, String mailContent)
			throws Exception {
		MimeMessage message;
		Session session;
		// 连接信息
		{
			Properties props = new Properties();
			// 协议与主机
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.host", "smtp.126.com");
			//邮件会话
			session = Session.getInstance(props);
			// 打印调试信息
			// session.setDebug(true);
		}
		
		// 邮件信息
		{
			message = new MimeMessage(session);// 由邮件会话新建一个消息对象
			message.setFrom(new InternetAddress(user));// 设置发件人的地址
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(
					toMail));// 设置收件人,并设置其接收类型为TO
			message.setSubject(mailTitle);
			// 发送HTML邮件,内容样式比较丰富
			message.setContent(mailContent, "text/html;charset=utf-8");
			// 设置发信时间
			message.setSentDate(new Date());
			message.saveChanges();
		}
		
		// 发送
		{
			Transport t = session.getTransport();
			t.connect(user, password);
			t.sendMessage(message, message.getAllRecipients());
			t.close();
		}
	}

	public static void main(String[] args) throws Exception {
		String user="xiaoming@126.com";
		String password="password";
		String content="hello 曹富帅";
		String title=content;
		String to="caoRichCool@Ctrip.com";
		sendMail(user, password,to, title,content);
	}
}

 类似资料: