JAVA电子邮件无法正常工作

时间:2014-11-26 12:11:08

标签: java spring spring-mvc amazon-ec2

我正在使用此代码从spring应用程序内部发送邮件

public static void main( final String[] args ) throws MessagingException
{
    System.out.println("<port> <username> <password> <to>");
    Properties props = new Properties();
    props.put("mail.smtp.auth",            "true");
    props.put("mail.smtp.starttls.enable",  "true");
    props.put("mail.smtp.host",             "smtp.mydomain.in");
    props.put("mail.smtp.port",             args[0].trim());

    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(args[1].trim(),args[2].trim());
            }
      });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(args[1].trim()));
    message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(args[3]));
    message.setSubject("test mail");
    message.setContent("test mail body","text/html");
    Transport.send(message);
}

Scanerio在哪里工作

  • 如果我在我的本地系统中运行它
  • 如果我在我的本地机器上使用我的弹簧应用程序
  • 如果我在AWS中单独运行

无法工作的地方

  • 如果我在AWS上使用我的spring应用程序它会抛出

    throws javax.mail.MessagingException'.
    javax.mail.AuthenticationFailedException: 535 5.7.8 Error: authentication failed:   authentication failure
    
        at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
        at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
        at javax.mail.Service.connect(Service.java:317)
        at javax.mail.Service.connect(Service.java:176)
        at javax.mail.Service.connect(Service.java:125)
        at javax.mail.Transport.send0(Transport.java:194)
        at javax.mail.Transport.send(Transport.java:124)
    

在我的实际应用程序中,我使用params:

    props.put("mail.smtp.auth",             env.getProperty("mail.smtp.auth").trim());
    props.put("mail.smtp.starttls.enable",  env.getProperty("mail.smtp.starttls.enable").trim());
    props.put("mail.smtp.host",             env.getProperty("mail.smtp.host").trim());
    props.put("mail.smtp.port",             env.getProperty("mail.smtp.port").trim());

    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(env.getProperty("username").trim(), env.getProperty("password").trim());
            }
      });

0 个答案:

没有答案