从java发送电子邮件

时间:2015-05-31 16:13:37

标签: java web-applications smtp

我正在尝试向我的网络应用程序的用户发送确认电子邮件,但我收到以下错误:

PKIX路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到所请求目标的有效证书路径

这是我的java类:

package it.bcsoft.onlinestore.mail;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class EmailSender {

    public static boolean sendEmail(String from, String pass, String message, String[] to)
    {
        String host="smtp.gmail.com";
        Properties props= System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", 25);
        props.put("mail.smtp.auth", "true");
        Session session= Session.getDefaultInstance(props, null);
        MimeMessage mime= new MimeMessage(session);
        try {
            mime.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress= new InternetAddress[to.length];
            for(int i=0; i<to.length; i++)
            {
                toAddress[i]= new InternetAddress(to[i]);
            }
            for(int i=0; i<toAddress.length;i++)
            {
                mime.addRecipient(RecipientType.TO, toAddress[i]);
            }
            mime.setSubject("Mail from onlinestore");
            mime.setText(message);
            Transport transport= session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(mime, mime.getAllRecipients());
            transport.close();
            return true;
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
}

我的PC上没有安装任何SMTP服务器,而且我使用的是java 1.7

1 个答案:

答案 0 :(得分:0)

确保使用正确的端口。要通过TLS使用Gmail的SMTP服务器,您必须使用端口587

Source

查看有关如何建立与Gmail的SMTP连接的this blog post