繁体   English   中英

从 java smtpapi 发送邮件

[英]sending mail from java smtpapi

我正在尝试使用 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

我不知道在主机地址中输入什么。

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

主机是

smtp.gmail.com

适用于 gmail

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

它应该工作。 但是请记住,要使这些邮件 api 正常工作,您应该从您的 gmail 帐户中启用 pop3 和 smtp。 并且没有额外的设置(比如 2-way security login 会阻止任何人使用来自其他 api 的 smtp/pop3 )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM