javax.mail 发送邮件

西门凯康
2023-12-01
import java.io.IOException;
import java.util.Properties;

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

public class EmailSender {

	private static String host = "";
	private static String port = "";
	private static String user = "";
	private static String nickName = "";
	private static String password = "";
	private static String runKey = "";
	private static Properties properties=new Properties();
	
	static{
		try {
			properties.load(EmailSender.class.getClassLoader().getResourceAsStream("/email.properties"));
			host = properties.getProperty("host");
			user = properties.getProperty("user");
			nickName=properties.getProperty("nickName");
			password = properties.getProperty("password");
			port = properties.getProperty("port");
			runKey=properties.getProperty("runKey");
		} catch (IOException e) {
			System.out.println("the configuration file is not exist");
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	public static void send(String to, String subject, String content) {
		if(runKey.equals("0")){
			return;
		}
		Properties props = new Properties();
		props.put("mail.smtp.host", host);// 指定SMTP服务器
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证
		try {
			Session mailSession = Session.getDefaultInstance(props);

			mailSession.setDebug(true);// 是否在控制台显示debug信息

			Message message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(user,nickName));// 发件人
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// 收件人	
			message.setSubject(subject);// 邮件主题
//			message.setContent(content, "text/html;charset=utf-8");
			message.setText(content);// 邮件内容
			message.saveChanges();

			Transport transport = mailSession.getTransport("smtp");
			transport.connect(host, user, password);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			System.out.println(e);
		}

	}
	
	public static void main(String[] args) {
		send("111111@qq.com", "111111", "11111");
	}

}


 类似资料: