martes, 2 de febrero de 2010

Enviar email desde Java 2º parte

Para usar el SMTP de google y nuestra cuenta de gmail tendremos que modificar el ejemplo anterior ya que google usa encriptación por SSL para la autenticación. A continuación el como se haría:


public class Main {
    
    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Esto sería el mensaje";
    private static final String emailSubjectTxt = "Aqui el asunto";
    private static final String emailFromAddress = "micuenta@gmail.com";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "Email destino"};
    
    
    public static void main(String args[]) throws Exception {
        
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        
        new Main().sendSSLMessage(sendTo, emailSubjectTxt,emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully Sent mail to All Users");
    }
    
    public void sendSSLMessage(String recipients[], String subject,String message, String from) throws MessagingException {
        boolean debug = true;
        
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        
        Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() {
            
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("micuenta@gmail.com", "micontraseñadegmail");
            }
        });
        
        session.setDebug(debug);
        
        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        
        
        msg.setSubject(subject);
        
        msg.setText(message);
        Transport.send(msg);
    }
}

1 comentario:

Jairo dijo...

estimado, necesito ayuda, ya puedo enviar correos por email con java, pero ahora me pidieron enviar uno con una imagen adjunta que se lee desde una base de datos como archivo blob, ya logre leer la imagen y la transforme en imagen, pero ahora no se como adjuntarla al mensaje...
ayuda please