javax.mail 发送邮件

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

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值