0

私は Java でメールを送信しようとしています。Google で検索したところ、いくつかのコードが見つかり、それを実行しようとしましたが、次の例外が発生しました。

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
    java.net.ConnectException: Connection timed out: connect

これが私のコードです:

public class SendMail {

  public static void Send(String username, String email) {

  Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", true); // added this line
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.user", "username@gmail.com");
    props.put("mail.smtp.password", "password");
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", true);

    Session session = Session.getInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    System.out.println("Port: " + session.getProperty("mail.smtp.port"));
    try {
      InternetAddress from = new InternetAddress("username");
      message.setSubject("Yes we can");
      message.setFrom(from);
      message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
      Multipart multipart = new MimeMultipart("alternative");
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText("your username :" + username);
      multipart.addBodyPart(messageBodyPart);
      messageBodyPart = new MimeBodyPart();
      String htmlMessage = "Our html text";
      messageBodyPart.setContent(htmlMessage, "text/html");
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart);
      Transport transport = session.getTransport("smtp");
      transport.connect("smtp.gmail.com", "username@gmail.com",  "password");
      System.out.println("Transport: " + transport.toString());
      transport.sendMessage(message, message.getAllRecipients());

    } catch (AddressException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MessagingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
4

3 に答える 3