Foros del Web » Programación para mayores de 30 ;) » Java »

cliente smtp en java ayuda!!!!!!

Estas en el tema de cliente smtp en java ayuda!!!!!! en el foro de Java en Foros del Web. hola que tal, soy nuevo en el foro espero puedan ayudarme en mi caso tengo que hacer un cliente de correo smtp que envie correo ...
  #1 (permalink)  
Antiguo 22/11/2010, 22:14
 
Fecha de Ingreso: noviembre-2010
Mensajes: 15
Antigüedad: 13 años, 4 meses
Puntos: 0
Pregunta cliente smtp en java ayuda!!!!!!

hola que tal, soy nuevo en el foro espero puedan ayudarme en mi caso

tengo que hacer un cliente de correo smtp que envie correo a una direccion cualquiera mi problema se basa en que en el campo SMTP SERVER no se que ponerle para poder enviar el correo porque me manda el siguiente error:

Error: java.net.ConnectException: Connection timed out: connect

no se como solucionarlo y soy principiante en este tipo de programacion, porfavor ayudenme este es el codigo que tengo hasta el momento, este cod me lo baje de una paggna y aparentemente funciona todo bien pero no se como enviar el correo....

package server;
import java.net.*;
import java.io.*;
import java.util.*;

public class server extends Thread {
// Servidor HTTP

Socket theConnection;
static File docroot;
static String indexfile = "index.html";

public server(Socket s) {
// Constructor
theConnection = s;
}

public static void main(String[] args) {
// El primer parámetro es el directorio raiz desde donde accede a las
// páginas, y el segundo parámetro es el número del puerto por el que
// escucha. Si no se pasan parámetros, toma el directorio actual y el
// puerto 80 por defecto.

int thePort;
ServerSocket ss;

// Captura el directorio raiz
try {
docroot = new File(args[0]);
}
catch (Exception e) {
// docroot = new File("./public_html"); // Toma el directorio public_html
docroot = new File("."); // Toma el directorio actual
}

// Captura el puerto para escuchar
/*
try {
thePort = Integer.parseInt(args[1]);
if (thePort < 0 || thePort > 65535) thePort = 80;
}
catch (Exception e) {
thePort = 80; // Toma el puerto 80 (default de HTTP server)
}*/
thePort=80;

try {
ss = new ServerSocket(thePort);
System.out.println("Aceptando conexiones en el puerto: " + ss.getLocalPort());
System.out.println("Directorio raiz: " + docroot);
System.out.println("Servidor HTTP en ejecucion...");
while (true) {
server s = new server(ss.accept());
s.start();
}
}
catch (IOException e) {
System.err.println("Servidor abortado");
}
}

public void run() {
// Llamado al thread

String method;
String ct;
String version = "";
File theFile;

try {
PrintStream os = new PrintStream(theConnection.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(theConnection.getInputStream())) ;
String get = br.readLine();
StringTokenizer st = new StringTokenizer(get);
method = st.nextToken();

if (method.equals("GET")) {
String file = st.nextToken();

if (file.endsWith("/")) // Si es un archivo html
file += indexfile;

ct = guessContentTypeFromName(file);
if (st.hasMoreTokens())
version = st.nextToken();

// Ciclo hasta el resto de las lineas de entrada
while ((get = br.readLine()) != null)
if (get.trim().equals(""))
break;
try {
theFile = new File(docroot, file.substring(1,file.length()));
FileInputStream fis = new FileInputStream(theFile);
byte[] theData = new byte[(int) theFile.length()];
// Necesita chequear el numero de bytes leidos hasta aqui
fis.read(theData);
fis.close();

if (version.startsWith("HTTP/")) { // Envia un encabezado MIME
os.print("HTTP/1.0 200 OK\r\n");
Date now = new Date();
os.print("Fecha: " + now + "\r\n");
os.print("Servidor: shttp 1.0\r\n");
os.print("Content-length: " + theData.length + "\r\n");
os.print("Content-type: " + ct + "\r\n\r\n");
}
// Envia el archivo
os.write(theData);
os.close();
} // fin del try
catch (IOException e) { // No pudo encontrar el archivo
if (version.startsWith("HTTP/")) { // Envie un encabezado MIME
os.print("HTTP/1.0 404 File not found\r\n");
Date now = new Date();
os.print("Date: " + now + "\r\n");
os.print("Server: shttp 1.0\r\n");
os.print("Content-type: text/html" + "\r\n\r\n");
}
os.println("<HTML><HEAD><TITLE>Archivo no encontrado</TITLE></HEAD>");
os.println("<BODY><H2>HTTP Error 404: Archivo no encontrado: " + file + "</H2></BODY></HTML>");
os.close();
}
}
else { // El metodo no es "GET"
if (version.startsWith("HTTP/")) { // Envia un encabezado MIME
os.print("HTTP/1.0 501 No Implementado\r\n");
Date now = new Date();
os.print("Fecha: " + now + "\r\n");
os.print("Servidor: shttp 1.0\r\n");
os.print("Content-type: text/html" + "\r\n\r\n");
}
os.println("<HTML><HEAD><TITLE>No Implementado</TITLE></HEAD>");
os.println("<BODY><H2>HTTP Error 501: No Implementado</H2></BODY></HTML>");
os.close();
}
}
catch (IOException e) {
}
try {
theConnection.close();
}
catch (IOException e) {
}
}

public String guessContentTypeFromName(String name) {
if (name.endsWith(".html") || name.endsWith(".htm"))
return "text/html";
else if (name.endsWith(".txt") || name.endsWith(".java"))
return "text/plain";
else if (name.endsWith(".gif"))
return "image/gif";
else if (name.endsWith(".jpg") || name.endsWith(".jpeg"))
return "image/jpeg";
else
return "text/plain";
}
}
  #2 (permalink)  
Antiguo 24/11/2010, 06:06
 
Fecha de Ingreso: abril-2007
Mensajes: 30
Antigüedad: 17 años
Puntos: 0
Respuesta: cliente smtp en java ayuda!!!!!!

prueba de esta manera, es bastante mas sencillo:

// Propiedades de la conexión
Properties props = new Properties();
props.setProperty("mail.smtp.host","tu host");
props.setProperty("mail.smtp.starttls.enable", "true");
props.setProperty("mail.smtp.port","tu puerto");

// Preparamos la sesion
Session session = Session.getDefaultInstance(props);
// Construimos el mensaje
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipients(Message.RecipientType.TO, listaEmails);
message.setSubject("menaje pruegba");

String mensajeHtml="aqui tu mensaje en html";
message.setContent(mensajeHtml, "text/html");
// Lo enviamos.
Transport t = session.getTransport("smtp");
t.connect();
t.sendMessage(message, message.getAllRecipients());

Etiquetas: correo, envio, servidores, smtp, cliente
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:02.