使用Javamail发送电子邮件

时间:2011-09-01 17:02:50

标签: javamail

我正在尝试使用我几天前使用Java邮件api注册的GoDaddy电子邮件主机发送邮件,但事实证明它并不那么容易实现, 我得到了,这个错误:

Could not connect to SMTP host: smtpout.asia.secureserver.net, port: 80, response: -1

我尝试过3535,465,587,25端口,但仍然遇到同样的错误。下面相同的代码已经过测试,可以使用Gmail发送电子邮件,并添加了此代码(在这种情况下我省略了):

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

MailSender.java:

   public class MailSender {

        private static String HOST = "smtpout.asia.secureserver.net";
        private static String PORT = "80";

        public static void sendMail(final Mail mail) throws MailException {

            EmailValidator validtor = new EmailValidator();

            if (validtor.validate(mail.getReceipient())) {
                Properties props = new Properties();
                props.put("mail.smtp.host", HOST);
                props.put("mail.smtp.socketFactory.port", PORT);           
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.port", PORT);

                Session session = Session.getDefaultInstance(props,
                        new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mail.getUsername(),mail.getPassword());
                            }
                        });

                try {
                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress(mail.getSender()));
                    message.setRecipients(Message.RecipientType.TO,
                            InternetAddress.parse(mail.getReceipient()));
                    message.setSubject(mail.getSubject());           
                    message.setText(mail.getBody());
                    Transport.send(message);
                    System.out.println("OK");

                } catch (MessagingException e) {
                    throw new MailException(e.getMessage());
                }           
            } else {
                throw new MailException("Email address not valid.");
            }       
        }
    }

此类中的Mail参数包含所有其他邮件信息,用户名/密码,发件人和收件人电子邮件地址字符串,经过测试可与Outlook& E等电子邮件客户端配合使用。雷鸟。

2 个答案:

答案 0 :(得分:2)

端口80用于HTTP。

将其更改为465或587。

(请参阅GoDaddy文档以获取正确的端口)

答案 1 :(得分:0)

显然,问题不在于Java mail api,而在GoDaddy服务器上,我已经咨询了他们的技术支持并且现在工作正常。

相关问题