send Email via Authenticator - Java Network

Java examples for Network:EMail

Description

send Email via Authenticator

Demo Code


import EJB.EjbUsuario;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main{
    public static void sendEmail(String host, String port,
            final String userName, final String password, String toAddress,
            String subject, String message) throws AddressException,
            MessagingException {//from   w  ww .j av  a 2  s. c  o m

        // sets SMTP server properties

        Properties properties = new Properties();

        properties.put("mail.smtp.host", "smtp.gmail.com");

        properties.put("mail.smtp.port", "587");

        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        "pruebatesisskynet@gmail.com", "skynet2000");
            }
        };

        Session session = Session.getInstance(properties, auth);
        // creates a new e-mail message
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(toAddress));
        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject("Recuperar contrase?a Bosque de Hiria");
        msg.setSentDate(new Date());
        Encriptado encriptado = new Encriptado();
        String encriptado1 = encriptado.Encriptar(message);
        String urlEncriptado = encriptado.encriptar(encriptado1);
        EjbUsuario ejbUsuario = new EjbUsuario();
        ejbUsuario.getUsuario().setKey(urlEncriptado);
        ejbUsuario.getUsuario().setUsername(message);
        String recuperarUser = ejbUsuario.actualizarLlave();

        msg.setText("");
        // sends the e-mail
        Transport.send(msg);

    }
}

Related Tutorials