2013-10-24 110 views
1

我有以下代碼發送電子郵件到我的gmail使用gmail smtp主機發送郵件時拒絕連接?

public class Mainclass { 

    public static void main(String args[]){ 


     String host = "smtp.gmail.com"; 
     String from = "[email protected]"; 
     String to = "[email protected]"; 

     // Set properties 
     Properties props = new Properties(); 
    props.put("mail.smtp.host", host); 
    props.put("mail.debug", true); 
    props.put("mail.smtp.auth", true); 
    props.put("mail.smtp.starttls.enable", true); 
    props.put("username", "[email protected]"); 
    props.put("password", "mypassword"); 

     // Get session 
     Session session = Session.getInstance(props); 

     try { 
      // Instantiate a message 
      Message msg = new MimeMessage(session); 

      // Set the FROM message 
      msg.setFrom(new InternetAddress(from)); 

      // The recipients can be more than one so we use an array but you can 
      // use 'new InternetAddress(to)' for only one address. 
      InternetAddress[] address = {new InternetAddress(to)}; 
      msg.setRecipients(Message.RecipientType.TO, address); 

      // Set the message subject and date we sent it. 
      msg.setSubject("Email from JavaMail test"); 
      msg.setSentDate(new Date()); 

      // Set message content 
     msg.setText("This is the text for this simple demo using JavaMail."); 

      // Send the message 
      Transport.send(msg); 

     } 
     catch (MessagingException mex) { 
      mex.printStackTrace(); 
     } 

    } 

} 

但是當我運行代碼時,我總是得到異常。

javax.mail.AuthenticationFailedException: failed to connect, no password specified? 
    at javax.mail.Service.connect(Service.java:329) 
    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) 
    at Mainclass.main(Mainclass.java:66) 

我在這裏丟失了什麼嗎?我的密碼是正確的。請幫幫我。

謝謝!

+0

您將主機指定爲'gmail',但您使用'fsdl.com'?那是什麼? –

+0

應該從地址有效嗎?謝謝! – user755806

回答

0

您是否正確設置了主機?另外,我沒有看到您使用哪個端口進行連接。你有沒有設置正確的端口? TLS是否是gmail的正確授權加密?

Please see the attached config: 
    'SMTP::TLS', 
    Host => 'smtp.gmail.com', 
    Port => 587, 
    User => '[email protected]', 
    Password => 'password' 
+0

什麼是'SMTP :: TLS'?謝謝! – user755806

相關問題