用java写邮箱发送的小案例

  • 来源:新网
  • 更新日期:2018-03-13

摘要:首先准备jar包 mail-1.4.7.jar maven:     javax.mail     mail     1.4.7 java代码: import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax

首先准备jar包

t0137aeb7444a5e886f.jpg

mail-1.4.7.jar

maven:

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

 

java代码:

import java.util.Properties;


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


public class JavaMailTest2 {
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.qq.com");
// 发送邮件协议名称
// props.setProperty("mail.transport.protocol", "smtp"); //163邮箱协议
props.setProperty("smtp.qq.com", "smtp");
//QQ邮箱需要加上端口,163不用
props.put("mail.smtp.port", "587");
// 设置环境信息
Session session = Session.getInstance(props, new Authenticator() {
// 在session中设置账户信息,Transport发送邮件时会使用
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("你的QQ邮箱账号pxdcz@qq.com", "POP3/SMTP或者IMAP/SMTP服务授权码");
}
});

// 创建邮件对象
Message msg = new MimeMessage(session);
// 发件人
msg.setFrom(new InternetAddress("你的QQ邮箱账号pxdcz@qq.com"));
// 多个收件人
// msg.setRecipients(RecipientType.TO, InternetAddress.parse("收件人QQ邮箱账号pxdcz@qq.com,收件人QQ邮箱账号pxdcz@qq.com"));
msg.setRecipients(RecipientType.TO, InternetAddress.parse("收件人QQ邮箱账号pxdcz@qq.com"));
// 抄送人
msg.setRecipient(RecipientType.CC, new InternetAddress("收件人QQ邮箱账号pxdcz@qq.com"));
// 暗送人
// msg.setRecipient(RecipientType.BCC, new InternetAddress("收件人QQ邮箱账号pxdcz@qq.com"));

// 主题
msg.setSubject("又有新消息咯!");
// HTML内容
msg.setContent("<div align="center">有新消息哟!快去查看!如果很忙,晚一丢丢也行哒。</div>", "text/html;charset=utf-8");

// 连接邮件服务器、发送邮件、关闭连接,全干了
Transport.send(msg);
}
}