2011-07-19 52 views
1

我想用Java程序和JavaMailApi發送郵件。我編寫了這個程序並擁有一個本地SMTPServer。這不是問題。我不知道要在主機地址中放置什麼。請看看我的代碼,並讓我知道我該怎麼做?從java發送郵件smtpapi

import java.util.*; 
    import javax.mail.*; 
    import javax.mail.internet.*; 
    import javax.activation.*; 

// Send a simple, single part, text/plain e-mail 
    public class TestEmail { 

     public static void main(String[] args) { 

     // SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!! 
      String to = "[email protected]"; 
      String from = "[email protected]"; 
     // SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!! 
      String host = "smtp.yourisp.net"; 

     // Create properties, get Session 
      Properties props = new Properties(); 

     // If using static Transport.send(), 
     // need to specify which host to send it to 
      props.put("mail.smtp.host", host); 
     // To see what is going on behind the scene 
      props.put("mail.debug", "true"); 
      Session session = Session.getInstance(props); 

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

      //Set message attributes 
       msg.setFrom(new InternetAddress(from)); 
       InternetAddress[] address = {new InternetAddress(to)}; 
       msg.setRecipients(Message.RecipientType.TO, address); 
       msg.setSubject("Test E-Mail through Java"); 
       msg.setSentDate(new Date()); 

      // Set message content 
       msg.setText("This is a test of sending a " + 
         "plain text e-mail through Java.\n" + 
         "Here is line 2."); 

      //Send the message 
       Transport.send(msg); 
     } 
      catch (MessagingException mex) { 
      // Prints all nested (chained) exceptions as well 
       mex.printStackTrace(); 
     } 
    } 
}//End of class 

回答

0

我不知道要放什麼東西在主機地址。

主機地址是您的SMTP服務器的IP地址或域名。

+0

但我告訴我有一個SMTP服務器軟件。在這種情況下要做什麼,如果我想chk我的程序能夠連接或不能.. – atul

+0

@atul:嘗試給您的SMTP服務器軟件駐留作爲主機地址的機器的IP或域名。 –

0

主機是

smtp.gmail.com 

爲gmail

props.put("mail.smtp.host", "smtp.gmail.com"); 

它應該工作。 但要記住這些郵件API工作,你應該從你的Gmail帳戶啓用POP3和SMTP。並沒有額外的設置(如雙向安全登錄防止任何人從其他apis使用smtp/pop3)。

+0

它只會工作,如果我有互聯網連接,但我不得不chk,我的程序會wrk或沒有互聯網連接的機器 – atul

+0

然後嘗試你的IP地址。或者不知道,因爲我沒有在我自己的郵件系統上測試它。 – peeyush

+0

好的,謝謝我試試:) – atul