Sending email using Javamail
I'm trying to send a mail using the GoDaddy email host I have registered couple of days ago using Java mail api, however it turns out that its not that easy to implement, and I am getting, this error:
Could not connect to SMTP host: smtpout.asia.secureserver.net, port: 80, response: -1
I have tried ports 3535, 465, 587, 25 but still get the same error. The same code below has been tested to work with sending out email using Gmail, with the addition of this code (which I have omitted in this case):
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.p开发者_如何学Cut("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.");
}
}
}
The Mail
parameter in this class holds all other mail information, the username/password, sender and recipient email address string, which is tested to work with email clients like Outlook & Thunderbird.
Port 80 is used for HTTP.
Change it to 465 or 587.
(Consult the GoDaddy documentation for the correct port)
Apparently, the problem was not with Java mail api, but was with GoDaddy server, I have consulted their tech support and work fine now.
精彩评论