从java smtpapi发送邮件

时间:2011-07-19 05:30:37

标签: java smtp

我正在尝试使用Java程序和JavaMailApi发送邮件。我编写了这个程序并拥有一个本地SMTPServer。这不是问题。我不知道在主持人地址放什么。请查看我的代码,让我知道该怎么办?

    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 = "vipan@vipan.com";
            String from = "vipan@vipan.com";
        // 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

2 个答案:

答案 0 :(得分:0)

  

我不知道该在主持人地址放什么。

主机地址是您的SMTP服务器的IP地址或域名。

答案 1 :(得分:0)

主持人

smtp.gmail.com

for gmail

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

它应该有用。 但请记住,要使这些邮件api正常工作,您应该从您的Gmail帐户启用pop3和smtp。并且没有额外的设置(例如双向安全登录阻止任何人使用来自其他api的smtp / pop3)。

相关问题