Entry
Can you send an email using JSP?
Feb 12th, 2002 07:25
Guillermo Taylor, katie betts,
Use this classes:
// HISTORIAL DE CAMBIOS DEL MODULO
//======================================================================
================================
// Fecha Version Autor Razon
// ---------- ------- --------- ------------------------------------
--------------------------------
// 03-12-2001 1 R.Udaondo Creación
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
/**
* Clase creada para el envío de correo mediante protocolo SMTP
*/
public class SMTPMail
{
/**
* Parsea las direcciones de correo desde una cadena con las
direcciones separadas por comas.
* @param addresses Cadena con las direcciones de correo
* @return Vector con las direcciones parseadas.
*/
static Vector parseAddresses( String addresses)
{
Vector vector = new Vector();
if ( addresses != null) {
StringTokenizer st = new StringTokenizer( addresses, ",");
while ( st.hasMoreTokens()) {
vector.add( st.nextToken());
}
}
return vector;
}
/**
* Parsea los attachments desde una cadena con los attachments
separados por comas.
* @param attachments Cadena con los attachments de correo
* @return Vector con los attachments parseados.
*/
static Vector parseAttachments( String attachments)
{
return parseAddresses( attachments);
}
/**
* Envia un correo por SMTP.
* @param host Dirección del host SMTP.
* @param fromAddress Dirección del remitente.
* @param toAddress Cadena con los destinatarios separados por
comas.
* @param subject Asunto del correo.
* @param text Texto del correo.
* @param textHtml Correo en html.
* @param fileAttachments Cadena con los attachments separados por
comas..
*/
protected static void send( String host, String fromAddress, String
toAddresses, String subject, String text, String htmlText, String
fileAttachments) throws AddressException, MessagingException
{
String smtpHost = host; // "192.168.197.5";
String from = fromAddress;
Vector to = parseAddresses( toAddresses);
Vector attachments = parseAttachments( fileAttachments);
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put( "mail.smtp.host", smtpHost);
// Get session
Session session = Session.getDefaultInstance( props, null);
// Define message
MimeMessage message = new MimeMessage( session);
// Message add FROM
message.setFrom( new InternetAddress( from));
// Message add TO
for ( Enumeration eToAddresses = to.elements();
eToAddresses.hasMoreElements();) {
message.addRecipient( Message.RecipientType.TO, new
InternetAddress( ( String) eToAddresses.nextElement()));
}
// Message add SUBJECT
message.setSubject( subject);
if ( attachments.size() == 0) {
// No Multi-part mail
message.setText( text);
} else {
// Create the multi-part
Multipart multipart = new MimeMultipart( ( htmlText == null
|| htmlText.length() == 0) ? "mixed" : "related");
// Create part text, Fill htmlText and add the part
BodyPart messageTextPart = new MimeBodyPart();
messageTextPart.setText( text + "\n");
multipart.addBodyPart( messageTextPart);
// Create part text, Fill htmlText and add the part
if ( htmlText != null || htmlText.length() > 0) {
BodyPart messageHtmlTextPart = new MimeBodyPart();
messageHtmlTextPart.setDataHandler( new DataHandler(
new SMTPByteArrayDataSource( htmlText, "text/html")));
multipart.addBodyPart( messageHtmlTextPart);
}
// Create part attachments, Fill attachments and add the
part
for ( Enumeration eAttachments = attachments.elements();
eAttachments.hasMoreElements();) {
String nameFile = ( String) eAttachments.nextElement();
BodyPart messageAttachmentsPart = new MimeBodyPart();
DataSource source = new FileDataSource( nameFile);
messageAttachmentsPart.setDataHandler( new DataHandler(
source));
messageAttachmentsPart.setHeader( "Content-ID",
nameFile);
messageAttachmentsPart.setFileName( ( new File(
nameFile)).getName());
multipart.addBodyPart( messageAttachmentsPart);
}
// Put parts in message
message.setContent( multipart);
}
// Send message
Transport.send( message);
}
/**
* Envia un correo por SMTP.
* @param host Dirección del host SMTP.
* @param fromAddress Dirección del remitente.
* @param toAddress Cadena con los destinatarios separados por
comas.
* @param subject Asunto del correo.
* @param text Texto del correo.
*/
public static void sendMail( String host, String fromAddress,
String toAddresses, String subject, String text) throws
AddressException, MessagingException
{
send( host, fromAddress, toAddresses, subject, text, null,
null);
}
/**
* Envia un correo por SMTP.
* @param host Dirección del host SMTP.
* @param fromAddress Dirección del remitente.
* @param toAddress Cadena con los destinatarios separados por
comas.
* @param subject Asunto del correo.
* @param text Texto del correo.
* @param fileAttachments Cadena con los attachments separados por
comas..
*/
public static void sendMail( String host, String fromAddress,
String toAddresses, String subject, String text, String
fileAttachments) throws AddressException, MessagingException
{
send( host, fromAddress, toAddresses, subject, text, null,
fileAttachments);
}
/**
* Envia un correo por SMTP.
* @param host Dirección del host SMTP.
* @param fromAddress Dirección del remitente.
* @param toAddress Cadena con los destinatarios separados por
comas.
* @param subject Asunto del correo.
* @param text Texto del correo.
* @param textHtml Correo en html.
* @param fileAttachments Cadena con los attachments separados por
comas..
*/
public static void sendMail( String host, String fromAddress,
String toAddresses, String subject, String text, String html, String
fileAttachments) throws AddressException, MessagingException
{
send( host, fromAddress, toAddresses, subject, text, html,
fileAttachments);
}
}
// HISTORIAL DE CAMBIOS DEL MODULO
//======================================================================
================================
// Fecha Version Autor Razon
// ---------- ------- --------- ------------------------------------
--------------------------------
// 03-12-2001 1 R.Udaondo Creación
import java.util.*;
import java.io.*;
import javax.activation.*;
/**
* DataSource para cualquier texto plano.
*/
public class SMTPByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
SMTPByteArrayDataSource( InputStream is, String type)
{
this.type = type;
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
int ch;
while ( ( ch = is.read()) != -1) {
os.write(ch);
}
data = os.toByteArray();
} catch (IOException ioex){}
}
SMTPByteArrayDataSource( byte[] data, String type)
{
this.data = data;
this.type = type;
}
SMTPByteArrayDataSource( String data, String type)
{
this.data = data.getBytes();
this.type = type;
}
public InputStream getInputStream() throws IOException
{
if ( data == null) {
throw new IOException( "No hay datos");
}
return new ByteArrayInputStream( data);
}
public OutputStream getOutputStream() throws IOException
{
throw new IOException( "No esta implementado");
}
public String getContentType()
{
return type;
}
public String getName()
{
return "dummy";
}
}