Como medida de seguridad del servidor, para evitar ataques externos, el usuario y contraseña del SMTP deben ser los correspondientes a la dirección remitente del mensaje. Además, habrá que autentificarse en el servidor POP antes de poder enviar.
Esto es un servlet que manda un email, autentificandose como POP antes de enviarlo:
Cartero.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Cartero{
public static boolean enviarMensaje(String destinatario,String asunto,String cuerpo){
try{
Properties props = new Properties();
props.put("mail.smtp.host", "SERVIDOR_MAIL_SMTP");
Session sesion = Session.getInstance(props);
// Tanto el usuario como la clave son de la cuenta de correo que envía el mensaje.
sesion.setPasswordAuthentication(new URLName("URL_DOMINIO_DE_ORIGEN"), new PasswordAuthentication("USUARIO_MAIL","CLAVE_MAIL"));
Store buzon=sesion.getStore("pop3");
buzon.connect("SERVIDOR_MAIL_POP", "USUARIO_MAIL", "CLAVE_MAIL");
buzon.close();
MimeMessage mensaje = new MimeMessage(sesion);
mensaje.setFrom(new InternetAddress("DIRECCION_DEL_REMITENTE"));
mensaje.addRecipient(Message.RecipientType.TO, new InternetAddress(destinatario));
mensaje.setSubject(asunto);
mensaje.setText(cuerpo);
try{
Transport mta = sesion.getTransport("smtp");
mta.connect();
try{
Transport.send(mensaje);
}catch(SendFailedException ex){return false;}
mta.close();
}catch(Exception ex){
System.out.println("Cartero: Error al enviar "+ex.toString());
}
}catch(Exception ex){return false;}
return true;
}
}
Esto es una JSP ejemplo que manda un email y captura los errores que pudiera haber:
<%@ page import = "java.util.HashMap,java.util.Vector,java.util.*,java.io.*,javax.mail.*,javax.mail.internet.*"%>
<html><head>
<title>Envio Mails</title>
</head>
<body>
<%
String to="destino@dominio.com";
Date sentDate=new Date();
String from="origen@dominio.com";
String subject="Concepto del mensaje";
String mensaje="cuerpo del mensaje";
String servidor="localhost";
String user="usuario"; //Debe ser el usuario correspondiente a la dirección de origen
String password="contraseña";
int estado=0;
String mensa="";
String mensa1="";
try
{
Properties props = new Properties();
props.put("mail.smtp.host", servidor);
Session newses = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(newses);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(sentDate);
msg.setText(mensaje);
msg.saveChanges();
Transport transport = newses.getTransport("smtp");
Store store = newses.getStore("pop3");
store.connect(servidor, user, password);
transport.connect(servidor, user, password);
transport.sendMessage(msg, msg.getAllRecipients());
}
catch (MessagingException mex)
{
Exception ex = mex;
if (ex instanceof SendFailedException) {
SendFailedException sfex = (SendFailedException)ex;
Address[] invalid = sfex.getInvalidAddresses();
if (invalid != null)
{
estado= 1;
mensa1="sendfailedexception";
}
Address[] validUnsent = sfex.getValidUnsentAddresses();
if (validUnsent != null)
{
estado= 2;
mensa1="validunsentaddrress";
}
Address[] validSent = sfex.getValidSentAddresses();
if (validSent != null)
{
estado= 3;
mensa1="validsentadrress";
}
}
if (ex instanceof MessagingException)
{
estado= 4;
mensa1="error de mansaje";
}else{
mensa1="error messanging desconocido";
estado= 5;
}
mensa=""+ex;
}
catch(Exception e)
{
mensa=""+e;
estado= 5;
}
%>
<br>
El resultado del envio ha sido:<br><br>
ESTADOS POSIBLES:<br>
0) Todo correcto<br>
4) Problemas con el servidor<br>
5) Problema no esperado<br><br>
Estado=<%out.print(estado);%><br><br>
Mensaje=<%out.print(mensa);%><br><br>
Mensaje1=<%out.print(mensa1);%>
</body>
</html>
Esto es un ejemplo que manda un email con un archivo de texto adjunto:
<%@
javax.mail.*,
javax.mail.event.*,
javax.mail.internet.*"
HttpSession ses = request.getSession();
ClaseError clasefallo = new ClaseError();
String id_correo=request.getParameter("correo");
MYBEAN2.Conectar();
String email_destinatario=MYBEAN2.Leer_Correo(id_correo);
MYBEAN2.Desconectar();
try
{
Properties p = new Properties();
Session s = Session.getInstance(p);
s.setPasswordAuthentication(new URLName("nombrepagina(ej.www.terra.es)"), new
PasswordAuthentication("codigo","password"));
MimeMessage message = new MimeMessage(s);
try
{
message.setFrom(new InternetAddress("DIRECCION CORREO ELECTRONICO DE ORIGEN"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("EMAIL DEL DESTINATARIO"));
message.setSubject("SUBJECT DEL EMAIL");
MimeMultipart mm = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
String ruta= application.getRealPath("/");
ruta=ruta+"/A_INFOALTALO.txt";
FileInputStream fr = new FileInputStream(ruta);
int size = fr.available();
String pepito="";
for ( int i = 0; i < size; i++ ) {
pepito+=(char)fr.read();
}
fr.close();
mbp.setContent(pepito,"text/html");
mm.addBodyPart(mbp);
message.setContent(mm);
message.setSentDate(new java.util.Date());
message.saveChanges();
}
catch(MessagingException e)
{
throw new Exception(clasefallo.mensaje);
}
try
{
Transport transport = s.getTransport("smtp");
transport.connect("servidor correo del servidor", "direccion correo electronico", "contraseña");
try
{
Transport.send(message);
}
catch(SendFailedException e)
{
throw new Exception(clasefallo.mensaje);
}
transport.close();
}
catch(NoSuchProviderException e)
{
throw new Exception(clasefallo.mensaje);
}
}
catch(Exception e) {
throw new Exception(clasefallo.mensaje);
}
%>