Ver Mensaje Individual
  #27 (permalink)  
Antiguo 09/01/2006, 22:27
Avatar de stock
stock
 
Fecha de Ingreso: junio-2004
Ubicación: Monterrey NL
Mensajes: 2.390
Antigüedad: 19 años, 10 meses
Puntos: 53
Tema: NET
Pregunta: como mandar correos con JAVA?
Respuesta: Para el envio de correos electronicos, primeramente necesitamos un servidor de correo ya sea SMTP, POP, IMAP, MIME, etc... para esta FAQ vamos a usar un SMTP, QMail que corre en un Gentoo, si quieres usar este mismo, pues aqui un tutorial de instalacion http://gentoo-wiki.com/HOWTO_Setup_Q...r_Mail_Servers sobre gentoo por supuesto!!.

OK, una vez instalado tu SMTP puedes usar las librerias para el envio de correos desarrolladas por la SUN, el JavaMail y la de JavaBeans, los cuales los puedes conseguir aqui:

http://java.sun.com/products/javamail/
http://java.sun.com/products/javabeans/glasgow/jaf.html

ok, luego de esto, metemos a nuestro classpath estas dos librerias, luego puedes usar el siguiente codigo para darte un ejemplo:

Código PHP:
/*
 * Created on Jan 9, 2006
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.smtp.SMTPTransport;

/**
 * @author crysfel
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class SendMail {

    private 
String myName;
    private 
String myMail;
    private 
String to;
    private 
String subject
    private 
String cc;
    private 
String bcc;
    private 
String url;
    private 
String mailhost;
    private 
String user
    private 
String password;
    private 
boolean auth;
    private 
String text;
    
    public 
void send()throws Exception{
        
String mailer "smtpsend";
        
boolean verbose false;
        
boolean ssl false;
        
        
//esto es para establecer el remitente
        
String from myName+"<"+myMail+">";
        
        try {
            
//tomamos las propiedades del sistema
            
Properties props System.getProperties();
            if (
mailhost != null)
                
props.put("mail.smtp.host"mailhost);
            
            if (
auth)
                
props.put("mail.smtp.auth""true");
            
            
Session session Session.getInstance(propsnull);
            
//creamos el objeto mensaje para enviar
            
Message msg = new MimeMessage(session);
            
            
//asignamos el remitente
            
if (from != null)
                
msg.setFrom(new InternetAddress(from));
            else
                
msg.setFrom();
            
            
//agregamos al destinatario
            
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(tofalse));
            
            
//si hay algo en el campo de CC lo asignamos a los destinatarios
            
if (cc != null)
                
msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(ccfalse));
            
//otra copia
            
if (bcc != null)
                
msg.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(bccfalse));
    
            
//asignamos el asunto del mensaje
            
msg.setSubject(subject);
            
//seleccionamos el envio del texto con formato html
            //si quieres que sea texto plano, puedes usar
            //la funcion 
            //msg.setText(text);
            //en lugar de esta:
            
msg.setContent(text,"text/html");
            
msg.setHeader("X-Mailer"mailer);
            
//la fecha de envio del mensaje
            
msg.setSentDate(new Date());

            
//creamos el objeto encargado de enviar el mensaje
            
SMTPTransport t = (SMTPTransport)session.getTransport(ssl "smtps" "smtp");
            try {
                
//si necesita autentificacion, nos conectamos con el usuario y pass  
                //si no tambien nos conectamos, pero sin autentificarnos
                
if (auth)
                    
t.connect(mailhostuserpassword);
                else
                    
t.connect();
                
//enviamos el mensaje a todos los destinatarios
                
t.sendMessage(msgmsg.getAllRecipients());
            } 
finally {
                if (
verbose)
                    
System.out.println("Respuesta del servidor smtp: " t.getLastServerResponse());
                
//cerramos la conexion con el SMTP
                
t.close();
            }
            
            
System.out.println("\n enviado con Exito!!.");

        } catch (
Exception e) {
            throw new 
Exception("<strong>Error al enviar el mail: </strong>"+e);
        }

    }
    
/**
     * @return Returns the auth.
     */
    
public boolean isAuth() {
        return 
auth;
    }
    
/**
     * @param auth The auth to set.
     */
    
public void setAuth(boolean auth) {
        
this.auth auth;
    }
    
/**
     * @return Returns the bcc.
     */
    
public String getBcc() {
        return 
bcc;
    }
    
/**
     * @param bcc The bcc to set.
     */
    
public void setBcc(String bcc) {
        
this.bcc bcc;
    }
    
/**
     * @return Returns the cc.
     */
    
public String getCc() {
        return 
cc;
    }
    
/**
     * @param cc The cc to set.
     */
    
public void setCc(String cc) {
        
this.cc cc;
    }
    
/**
     * @return Returns the mailhost.
     */
    
public String getMailhost() {
        return 
mailhost;
    }
    
/**
     * @param mailhost The mailhost to set.
     */
    
public void setMailhost(String mailhost) {
        
this.mailhost mailhost;
    }
    
/**
     * @return Returns the myMail.
     */
    
public String getMyMail() {
        return 
myMail;
    }
    
/**
     * @param myMail The myMail to set.
     */
    
public void setMyMail(String myMail) {
        
this.myMail myMail;
    }
    
/**
     * @return Returns the myName.
     */
    
public String getMyName() {
        return 
myName;
    }
    
/**
     * @param myName The myName to set.
     */
    
public void setMyName(String myName) {
        
this.myName myName;
    }
    
/**
     * @return Returns the password.
     */
    
public String getPassword() {
        return 
password;
    }
    
/**
     * @param password The password to set.
     */
    
public void setPassword(String password) {
        
this.password password;
    }
    
/**
     * @return Returns the subject.
     */
    
public String getSubject() {
        return 
subject;
    }
    
/**
     * @param subject The subject to set.
     */
    
public void setSubject(String subject) {
        
this.subject subject;
    }
    
/**
     * @return Returns the text.
     */
    
public String getText() {
        return 
text;
    }
    
/**
     * @param text The text to set.
     */
    
public void setText(String text) {
        
this.text text;
    }
    
/**
     * @return Returns the to.
     */
    
public String getTo() {
        return 
to;
    }
    
/**
     * @param to The to to set.
     */
    
public void setTo(String to) {
        
this.to to;
    }
    
/**
     * @return Returns the user.
     */
    
public String getUser() {
        return 
user;
    }
    
/**
     * @param user The user to set.
     */
    
public void setUser(String user) {
        
this.user user;
    }

OK, ahora la implementacion de esa clase, seria algo como esto:
Código PHP:
/*
 * Created on Jan 9, 2006
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author crysfel
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class ImplementaMail {
    public static 
void main(String arg[]){
        
//creamos el objeto para el envio del correo
        
SendMail mail = new SendMail();
        
        
//datos del servidor SMTP
        
mail.setMailhost("localhost");
        
mail.setAuth(true);
        
mail.setUser("root");
        
mail.setPassword("");
        
        
//datos del remitente
        
mail.setMyName("Crysfel Villa");
        
mail.setMyMail("[email protected]");
        
        
//datos del destinatario
        
mail.setTo("[email protected]");
        
mail.setCc("[email protected]");
        
mail.setSubject("Probando el HTML!!");
        
mail.setText("Esta es una prueba del objeto <b>SendMail.java</b> <br><br><center>usando HTML</b><br><br><img src=\"http://pulso.um.edu.mx/~crysfel/pictures/chiles/chiles3.jpg\">");
        
        try{
            
//enviamos el mensaje!!
            
mail.send();
        }catch(
Exception e){
            
System.out.println(e);
        }
    }

Bueno, esto es todo!! espero le pueda servir a alguien!!

have funnnnnnnnnnnn

Última edición por stock; 24/02/2007 a las 20:41