最近项目需求要发邮件,研究了一下邮箱发送的方法,代码网上很多,用main方法进行了测试,成功的将邮件发到了同学的qq邮箱
public static void main(String[] args) throws MessagingException {
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.163.com");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 设置环境信息
Session session = Session.getInstance(props);
// 创建邮件对象
Message msg = new MimeMessage(session);
msg.setSubject("你好,这是我用javamail发送的一个邮件");
msg.setText(""); //邮件的内容
// 设置发件人
msg.setFrom(new InternetAddress("123@163.com"));
Transport transport = session.getTransport();
// 连接邮件服务器
transport.connect("123@163.com", "授权码");
// 发送邮件
transport.sendMessage(msg, new Address[] {new InternetAddress("123@qq.com")});
// 关闭连接
transport.close();
}
代码很简单, 但值得注意的几个地方有:
1.导入jar包 (在网上自己下载)
2.我用的是网易邮箱进行发送,要打开pop3/SMTP/IMAP,不然会报错
3.密码用授权码
4. 将其封装成一个方法就可以在项目中用啦