2016-04-21 3 views
0

私はhttp://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.htmlのチュートリアルで、JavaMail APIで電子メールを送信する方法を示しています。私はWEBアプリでメールを送信しようとするとJavaMail APIでGmailを操作するのに問題があります

は、だから私は、次のコードスニペットに

public class EmailSessionBean { 

private int port = 465; 
private String host = "smtp.gmail.com"; 
private String from = "[email protected]"; 
private boolean auth = true; 
private String username = "[email protected]"; 
private String password = "mypassword"; 
private Protocol protocol = Protocol.SMTPS; 
private boolean debug = true; 

public void sendEmail(String to, String subject, String body) { 

    // Create a Properties object to contain settings for 
    // the SMTP protocol provider. 
    Properties props = new Properties(); 
    props.put("mail.smtp.host", host); 
    props.put("mail.smtp.port", port); 
    switch (protocol) { 
     case SMTPS: 
      props.put("mail.smtp.ssl.enable", true); 
      break; 
     case TLS: 
      props.put("mail.smtp.starttls.enable", true); 
      break; 
    } 

    // If SMTP authentication is required you must set the mail.smtp.auth 
    // property and construct a Authenticator instance that returns 
    // a PasswordAuthentication instance with your username and password. 
    Authenticator authenticator = null; 
    if (auth) { 
     props.put("mail.smtp.auth", true); 
     authenticator = new Authenticator() { 
      private PasswordAuthentication pa 
        = new PasswordAuthentication(username, password); 

      @Override 
      public PasswordAuthentication getPasswordAuthentication() { 
       return pa; 
      } 
     }; 
    } 

    //Create a Session instance using the Properties object 
    // and the Authenticator object. 
    Session session = Session.getInstance(props, authenticator); 
    session.setDebug(debug); 

    // Construct a MimeMessage instance, populate the message headers 
    // and content and then send the message 
    MimeMessage message = new MimeMessage(session); 
    try { 
     message.setFrom(new InternetAddress(from)); 
     InternetAddress[] address = {new InternetAddress(to)}; 
     message.setRecipients(Message.RecipientType.TO, address); 
     message.setSubject(subject); 
     message.setSentDate(new Date()); 
     message.setText(body); 
     Transport.send(message); 
    } catch (MessagingException ex) { 
     ex.printStackTrace(); 
    } 
} 
} 

を書いて、Gmailのはそれをやってから私を停止し、私は、「サインイン阻止しよう」メール。

P.S.私はまた、私のGmailアカウントで「安全性の低いアプリのアクセス」を無効にしました。しかし、次のGmailの試みで、アカウントが停止されました。

有用なコメント/解決策があります。

答えて

関連する問題