简体   繁体   中英

Sending email using a servlet

I have to send an email through a servlet, I have tried a bunch of codes, but none of them work with an gmail account, any ideas?

 java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");

        Authenticator auth =  new SMTPAuthenticator();
        //auth = null;
        Session sess = Session.getInstance(props, auth);

        sess.setDebug(false);
           // -- Create a new message --
           Message msg = new MimeMessage(sess);

           // -- Set the FROM and TO fields --
           msg.setFrom(new InternetAddress("myemail@gmail.com"));
           msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
             "sendtoemail", false));
           msg.setSubject("Test");
           msg.setText("Yippe");
           msg.setSentDate(new Date());
           Transport.send(msg);

           public class SMTPAuthenticator extends javax.mail.Authenticator {
           @Override
           public PasswordAuthentication getPasswordAuthentication() {
           String username = "myemail@gmail.com";
           String password = "mypass";
           return new PasswordAuthentication(username, password);
           }

}

This Code throws javax.mail.MessagingException: Could not convert socket to TLS exception

Just switching to commons-email won't еliminate this exception. Moreover switching to commons-email would result in reducing the amount of useful information within the exception - the following lines from the exception log won't be present anymore:

nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: 
    sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

The real lead in this case is within the nested exception.

To fix it you need to install the email server certificate to the JVM keystore. The location of the default keystore depends on the java distribution. In my case it was /etc/java-6-sun/security/cacert

After I added the certificate the authentication succeeded.

using commons-email

public static Email createMail(){
    Email email = SimpleEmail();


    email.setHostName(Settings.getValue("smtp.host"));
    email.setSmtpPort(Integer.parseInt(Settings.getValue("smtp.port")));
    String username = Settings.getValue("smtp.user");
    if (username.length() > 0) {
        email.setAuthentication(username, Settings.getValue("smtp.password"));
    }

    boolean useSSL = false;
    try {
        useSSL = Boolean.parseBoolean(Settings.getValue("smtp.ssl"));
    } catch (Exception ex) {
        // ignore - property not set
    }

    email.setSSL(useSSL);
    email.setCharset("utf-8");

    return email;
}

public sendMail(String recipientEmail) {
     Email email = createMail();
     email.addTo(recipientEmail);
     email.setFrom("no-reply@example.org");
     email.setSubject("Your subject herE");
     email.setMsg("Your message here");
     email.send();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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