2017-04-14 11 views
0

JavaアプリケーションからGmailアカウントに電子メールを送信したい次のコードとjavaMail APIを使用しましたが、Gmailはユーザー名とパスワードを受け入れず例外がスローされました 誰でも助けてくれますか?この問題を解決するにはどうすればよいですか?JavaMail API:ユーザー名とパスワードが受け入れられません(Gmail)

MailService.java

public class MailService { 

    String email; 
    String content; 
    public void sendMail(String email,String content) 
    { 
     this.email=email; 
     this.content=content; 
     // Recipient's email ID needs to be mentioned. 
      String to = email; 

      // Sender's email ID needs to be mentioned 
      String from = [email protected]; 
      final String username = "myusername";//change accordingly 
      final String password = "*******";//change accordingly 

      // Assuming you are sending email through relay.jangosmtp.net 
      String host = "smtp.gmail.com"; 

      Properties props = new Properties(); 
      props.put("mail.smtp.auth", "true"); 
      props.put("mail.smtp.starttls.enable", "true"); 
      props.put("mail.smtp.host", host); 
      props.put("mail.smtp.port", "587"); 

      // Get the Session object. 
      Session session = Session.getInstance(props, 
      new javax.mail.Authenticator() { 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(username, password); 
      } 
      }); 

      try { 
      // Create a default MimeMessage object. 
      Message message = new MimeMessage(session); 

      // Set From: header field of the header. 
      message.setFrom(new InternetAddress(from)); 

      // Set To: header field of the header. 
      message.setRecipients(Message.RecipientType.TO, 
        InternetAddress.parse(to)); 

      // Set Subject: header field 
      message.setSubject("Did you get my message?"); 

      // Now set the actual message 
      message.setText(content); 

      // Send message 
      Transport.send(message); 

      System.out.println("Sent message successfully...."); 

      } catch (MessagingException e) { 
      throw new RuntimeException(e); 
      } 
     } 
    } 
+1

[JavaMail with Gmail:535-5.7.1ユーザー名とパスワードは受け入れられません](http://stackoverflow.com/questions/2965251/javamail-with-gmail-535-5-7-1-username - およびパスワードは受け入れられません) –

答えて

1

は、Gmailアカウントを経由してメールを送信できるようにするには、Googleアカウントのセキュリティ設定で(アプリケーションがビューのGmailのポイントである)非セキュアなアプリケーションを可能にしなければなりません。 enter image description here

UPD: また、あなたがデバッグメッセージを表示したい場合は、次のJavaのメールプロパティを使用します。

props.put("mail.debug", "true"); 

それは舞台裏で起こって何かを見つけるためにあなたを助けることができます。

+1

これと多くの関連トピックは、[JavaMail FAQ](http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmailauth)で説明されています。 –

関連する問題