Send email with java

Asked

Viewed 2,491 times

-1

Good afternoon. I’m using java, JPA, wildfly and primefaces. You need to send a notification email after the user clicks on the send button. How do I send emails through java?

1 answer

1

The best API for this is the Javamail. To use it you will need an email provider (for the example I mention it would be one of gmail). For example, the email sending code using SSL would look like this:

public class SendMailSSL {
public static void main(String[] args) {
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("[email protected]"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler," +
                "\n\n No spam to my email, please!");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
}

It’s just an example, but it can vary depending on the form of authentication and email provider used. Take a look at this article, which is where I got the above example using SSL.

  • Giuliana tested and gave the following error: "Caused by: java.lang.Runtimeexception: javax.mail.Authenticationfailedexception: 534-5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtT"......

  • 1

    Did you create the email provider and set its user and password in the above example in getPasswordAuthentication? If yes, the error is not trivial then would need the full stacktrace to identify the problem.

  • I’ve been traveling, so the delay, come on I managed to solve the problem, I set up getPasswordAuthentication and it’s working perfectly.

  • Show! Mark as answered to help other people :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.