当前位置:   article > 正文

java 邮件发送的几种方式_java 发送邮件

java 发送邮件

1、使用JavaMail发送邮件

1.1 添加依赖

  1. <dependency>
  2. <groupId>javax.mail</groupId>
  3. <artifactId>mail</artifactId>
  4. <version>1.4.3</version>
  5. </dependency>

1.2 简单邮件发送

  1. @Test()
  2. public void testSend() throws Exception {
  3. // 连接邮件服务器的参数配置
  4. Properties props = new Properties();
  5. // 设置用户的认证方式
  6. props.setProperty("mail.smtp.auth", "true");
  7. props.put("mail.smtp.host", host);
  8. props.put("mail.smtp.port", port);
  9. // 创建定义整个应用程序所需的环境信息的 Session 对象
  10. Session session = Session.getInstance(props,new Authenticator() {
  11. protected PasswordAuthentication getPasswordAuthentication() {
  12. return new PasswordAuthentication(name, pwd);
  13. }
  14. });
  15. // 创建消息对象
  16. MimeMessage message = new MimeMessage(session);
  17. // 邮件消息头
  18. message.setFrom(new InternetAddress(name)); // 发件人
  19. message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 收件人
  20. message.setSubject("邮件测试1");
  21. message.setText("Hello, java mail!");
  22. // 发送邮件
  23. Transport.send(message);
  24. }

2、使用Spring的JavaMailSenderImpl发送邮件

2.1 添加依赖

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-context-support</artifactId>
  4. <version>4.3.14.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>javax.mail</groupId>
  8. <artifactId>mail</artifactId>
  9. <version>1.4.3</version>
  10. </dependency>

2.2 简单邮件发送

  1. @Test
  2. public void testSend2() throws MessagingException {
  3. JavaMailSenderImpl sendService = new JavaMailSenderImpl();
  4. sendService.setHost(host);
  5. sendService.setPort(port);
  6. sendService.setUsername(name);
  7. sendService.setPassword(pwd);
  8. MimeMessage msg = sendService.createMimeMessage();
  9. MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
  10. helper.setTo(to);
  11. helper.setFrom(name);
  12. helper.setSubject("邮件测试2");
  13. helper.setText("Hello, spring!", true);
  14. sendService.send(msg);
  15. }

3、使用Apache commons-email发送邮件

3.1 添加依赖

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-email</artifactId>
  4. <version>1.4</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>javax.mail</groupId>
  8. <artifactId>mail</artifactId>
  9. <version>1.4.3</version>
  10. </dependency>

3.2 简单邮件发送

  1. @Test
  2. public void testSend3() throws EmailException {
  3. Email email = new SimpleEmail();
  4. email.setHostName(host);
  5. email.setSmtpPort(port);
  6. email.setAuthenticator(new DefaultAuthenticator(name, pwd));
  7. email.setCharset("UTF-8");
  8. email.setFrom(name);
  9. email.addTo(to);
  10. email.setSubject("测试邮件3");
  11. email.setMsg("Hello, commons-email!");
  12. email.send();
  13. }

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

闽ICP备14008679号