使用Java给qq邮箱发邮件实例

时间:2022-08-21 19:02:51

1.QQ邮箱设置

  1.1 进去QQ邮箱-->设置-->账号-->进行设置如下图

  使用Java给qq邮箱发邮件实例

2.foxmail设置(由于我要利用它收邮件)

  2.1 参照官方的设置即可 http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=371

  ps:填写的邮箱密码是独立密码:需要注意的就是SSL链接要勾选;smtp端口是465

3.Java中代码配置(导入javax.mail.jar,如果jdk低于6,则需导入javax.activation.jar(用来出来MIME类型内容))

  3.1 发送邮件配置代码

//发送邮箱验证
try {
Properties prop
= new Properties();
prop.setProperty(
"mail.transport.protocol", "smtp");
prop.setProperty(
"mail.smtp.host", "smtp.qq.com");
prop.setProperty(
"mail.smtp.auth", "true");
prop.put(
"mail.smtp.port","465");
       prop.put("mail.smtp.ssl.enable", "true");
 prop.setProperty(
"mail.debug", "true");
Authenticator authenticator
= new EmailAuthenticator("1274444444@qq.com", "密码(此处密码为从QQ邮箱的【设置】->【账户】->【POP3/IMAP/SMTP...】中获取的授权码)"); //创建会话 Session session = Session.getInstance(prop,authenticator); //填写信封写信 Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("1271099894@qq.com")); msg.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail())); msg.setSubject(user.getUsername()+"激活邮箱!"); msg.setContent(user.getUsername()+",你好请到这个地址激活你的账号:http://www.estore.com/ActiveServlet?activecode="+user.getActivecode() ,"text/html;charset=utf8"); //验证用户名密码发送邮件 Transport transport = session.getTransport(); //transport.connect("1274444444@qq.com","qq邮箱验证码"); transport.send(msg); transport.close(); }
        

  3.2辅助类

     public class EmailAuthenticatorextends Authenticator {
String userName
= null;
String password
= null;
public PopAuthenticator() {
}
public PopAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}