当前位置:   article > 正文

Java:javax.mail通过163服务器发送邮件_java 网易邮箱设置发送邮件

java 网易邮箱设置发送邮件
  1. <dependency>
  2. <groupId>javax.mail</groupId>
  3. <artifactId>mail</artifactId>
  4. <version>1.4.7</version>
  5. </dependency>
  1. package com.example.demo;
  2. import javax.mail.*;
  3. import javax.mail.internet.InternetAddress;
  4. import javax.mail.internet.MimeMessage;
  5. import java.util.Properties;
  6. public class SendEmail {
  7. public static Properties getProperties(){
  8. Properties properties = new Properties();
  9. // 开启debug调试
  10. properties.setProperty("mail.debug", "true");
  11. // 邮件服务器
  12. properties.setProperty("mail.smtp.host", "smtp.163.com");
  13. // 端口号
  14. properties.setProperty("mail.smtp.port", "25");
  15. // 需要身份验证
  16. properties.setProperty("mail.smtp.auth", "true");
  17. // 发送邮件协议
  18. properties.setProperty("mail.transport.protocol", "smtp");
  19. properties.setProperty("mail.smtp.ssl.enable", "true");
  20. return properties;
  21. }
  22. public static void main(String[] args) {
  23. // 发件人
  24. String fromUser = "xxx@163.com";
  25. // 客户端授权码
  26. String password = "xxx";
  27. // 收件人
  28. String toUser = "xxx@qq.com";
  29. // 获取默认session对象
  30. Session session = Session.getInstance(getProperties());
  31. try {
  32. // 创建默认的 MimeMessage 对象
  33. MimeMessage message = new MimeMessage(session);
  34. // 发送人
  35. message.setFrom(new InternetAddress(fromUser));
  36. // 接收人
  37. message.addRecipient(Message.RecipientType.TO,
  38. new InternetAddress(toUser));
  39. // 标题
  40. message.setSubject("This is the Subject Line!");
  41. // 消息体
  42. //message.setText("This is actual message");
  43. //设置消息体StringhtmlContent="<h1>Hello World!</h1><p>This is a HTML email.</p>";
  44. message.setContent("htmlContent", "text/html;charset=utf-8");
  45. // 发送消息
  46. Transport transport = session.getTransport();
  47. transport.connect(fromUser, password);
  48. transport.sendMessage(message, new Address[]{new InternetAddress(toUser)});
  49. transport.close();
  50. System.out.println("Sent message successfully....");
  51. } catch (MessagingException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. }

SpringBoot项目部署到服务器上无法发送邮件解决方式

错误一:

trying to connect to host “smtp.163.com”, port 25, isSSL false

在发送邮件的类加上: props.put("mail.smtp.ssl.enable", true);

错误二:

trying to connect to host “smtp.163.com”, port 25, isSSL true

  1. 将SMTP端口号25改为465
  2. props.put("mail.smtp.port", "465");

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/591828
推荐阅读
相关标签
  

闽ICP备14008679号