2011-02-12 146 views
0

我正在嘗試使用Java發送電子郵件。從閱讀中,我發現,如果我使用Gmail作爲主機,我可以免費做這個&它應該工作,這是正確的。發送電子郵件:連接到主機時出現問題

所以,我有我下面的代碼,&我試圖從自己發送一封電子郵件給我的朋友的電子郵件(在我下面的代碼已經被改變了隱私的電子郵件),但我得到的時候我去送拋出的異常/傳送電子郵件(在該行Transport.send(MSG))

引發的輸出/異常是:

javax.mail.MessagingException的:無法連接到SMTP主機:smtp.gmail。 com,port:25; 嵌套的例外是: java.net.ConnectException:連接超時:連接 本應成功:假

你覺得我做錯了嗎?

/** 
* SimpleAuthenticator is used to do simple authentication 
* when the SMTP server requires it. 
*/ 
class SMTPAuthenticator extends javax.mail.Authenticator 
{ 

    public PasswordAuthentication getPasswordAuthentication() 
    { 
     String username = "[email protected]"; 
     String password = "xxxxxxx"; 
     return new PasswordAuthentication(username, password); 
    } 
} 

public class SendEmail 
{ 

    public SendEmail() 
    { 

    } 

    public static boolean sendEmail(String from, String to[], String subject, String body) 
    { 
     try 
     { 
      boolean debug = false; 

      // Set the host smtp address 
      Properties props = new Properties(); 
      props.put("mail.smtp.host", "smtp.gmail.com"); // "smtp.jcom.net"); 
      props.put("mail.smtp.auth", "true"); 

      // create some properties and get the default Session 
      // Session session = Session.getDefaultInstance(props, null); 
      Authenticator auth = new SMTPAuthenticator(); 
      Session session = Session.getDefaultInstance(props, auth); 
      session.setDebug(debug); 

      // create a message 
      Message msg = new MimeMessage(session); 

      // set the from and to address 
      InternetAddress addressFrom = new InternetAddress(from); 
      msg.setFrom(addressFrom); 

      InternetAddress[] addressTo = new InternetAddress[to.length]; 
      for (int i = 0; i < to.length; i++) 
      { 
       addressTo[i] = new InternetAddress(to[i]); 
      } 
      msg.setRecipients(Message.RecipientType.TO, addressTo); 

      // Optional : You can also set your custom headers in the Email if 
      // you Want 
      msg.addHeader("MyHeaderName", "myHeaderValue"); 

      // Setting the Subject and Content Type 
      msg.setSubject(subject); 
      msg.setContent(body, "text/plain"); 

      System.out.println("1"); 
      Transport.send(msg); 
      System.out.println("2"); 
     } 
     catch (Exception e) 
     { 
      System.out.println(e); 
      return false; 
     } 

     return true; 
    } 

    public static void main(String args[]) 
    { 
     boolean res = SendEmail.sendEmail("[email protected]", new String[] {"[email protected]", "[email protected]"}, 
              "Test", "Did it work?"); 
     System.out.println("Should have succeeded: " + res); 
    } 

} 

回答