Mostrando entradas con la etiqueta java. Mostrar todas las entradas
Mostrando entradas con la etiqueta java. Mostrar todas las entradas

miércoles, 14 de noviembre de 2007

Envio de emails con Gmail

Aquí teneis un pequeño ejemplo de como enviar correos con Gmail:


import java.security.Security;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class GmailWrapper {

private static final String MAIL_SERVER = "smtp.gmail.com";
private static final String MAIL_PORT = "465";
private static final String MAIL_FROM = "from@gmail.com";
private static final String MAIL_USER = "user@gmail.com";
private static final String MAIL_PASSWORD = "password";

public void sendRememberMail(String username, String password, String to) {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

String msgBody = "The message you want to sent";
String msgSubject = "Mail subject";

Properties properties = new Properties();

properties.put("mail.smtp.user", MAIL_FROM);
properties.put("mail.smtp.password", MAIL_PASSWORD);
properties.put("mail.smtp.host",MAIL_SERVER);
properties.put("mail.smtp.port", MAIL_PORT);
properties.put("mail.smtp.starttls.enable","true");
properties.put( "mail.smtp.auth", "true");
properties.put("mail.smtp.debug", "false");
properties.put("mail.from",MAIL_FROM);
properties.put("mail.smtp.socketFactory.port", MAIL_PORT);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");

try {

Authenticator auth = new MyAuthenthicator();
Session session = Session.getInstance(properties, auth);
session.setDebug(false);
Message message = new MimeMessage(session);
InternetAddress[] address = {new InternetAddress(to)};
message.setRecipients(Message.RecipientType.TO, address);
message.setFrom(new InternetAddress(MAIL_FROM));
message.setSubject(msgSubject);
message.setText(msgBody);

BodyPart messageBodyPart = new MimeBodyPart();
String messageText = msgBody;
messageBodyPart.setText(messageText);

Multipart mPart = new MimeMultipart();
BodyPart body = new MimeBodyPart();
body.setContent(msgBody,"text/plain");
mPart.addBodyPart(body);

message.setContent(mPart);
message.saveChanges();

Transport transport = session.getTransport(address[0]);
transport.connect();

transport.sendMessage(message,address);
} catch (Exception e) {
// Catch exception
}
}

public class MyAuthenthicator extends Authenticator {

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MAIL_USER,MAIL_PASSWORD);
}
}
}