2011-07-19 54 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