首页 > 解决方案 > java邮件javax.mail.MessagingException:异常

问题描述

下面是我用于测试目的的代码(我使用了与我的项目中使用的相同的库)。

package test;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class EmailSender {
  public static void send(String from, String password, String to, String sub, String msg) {
    // Get properties object
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    // get Session
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(from, password);
      }
    });
    // compose message
    try {
      MimeMessage message = new MimeMessage(session);
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setFrom(new InternetAddress("sannavdev@gmail.com"));
      message.setSubject(sub);
      message.setText(msg);
      // send message
      Transport.send(message);
      System.out.println("message sent successfully");
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }

  }

  public static void main(String[] args) {


    final String fromEmail = "sannavdev@gmail.com"; // requires valid gmail id
    final String password = "sannavdev@1234"; // correct password for gmail id
    final String toEmail = "vethsa.teja@broadcom.com"; // can be any email id

    EmailSender.send(fromEmail, password, toEmail, "hello javatpoint", "How r u?");
  }
}

代码在eclipse中运行良好。但是当我在 IPV 6 环境中运行代码时,出现以下错误:

发送邮件失败 javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:465;嵌套异常是:java.net.SocketTimeoutException:连接超时

标签: javaemail

解决方案


推荐阅读