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

Error al enviar email

Estas en el tema de Error al enviar email en el foro de .NET en Foros del Web. Hola. Tengo un codigo que adjunto para enviar emails desde mi pagina aspx, solamente funciona con el dominio de mi empresa y si pongo algún ...
  #1 (permalink)  
Antiguo 12/02/2014, 11:00
 
Fecha de Ingreso: noviembre-2013
Mensajes: 18
Antigüedad: 10 años, 6 meses
Puntos: 0
Error al enviar email

Hola.

Tengo un codigo que adjunto para enviar emails desde mi pagina aspx, solamente funciona con el dominio de mi empresa y si pongo algún dominio exterior obtengo este mensaje.
Mailbox unavailable. The server response was: 5.7.1 Unable to relay

Alguna idea?

Código ASP:
Ver original
  1. Dim smtpserver As New SmtpClient("127.0.0.1")
  2.         ' smtpserver.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
  3.         Dim mail As New MailMessage()
  4.         smtpserver.Credentials = New Net.NetworkCredential("[email protected]", "A34hf1o55toog")
  5.         smtpserver.Port = 25
  6.         smtpserver.Host = "mail.midominio.com"
  7.         mail = New MailMessage()
  8.         mail.From = New MailAddress("[email protected]")
  9.         mail.To.Add("[email protected]")
  10.         mail.Subject = "Propuesta económica" & "  Número:  " & TextIDPropuesta.Text
  11.         mail.Body = "Tal como hemos estado comentado le adjunto propuesta económica :"
  12.  
  13.         ' Dim att As New System.Net.Mail.Attachment("RUTAARCHIVO.EXT")
  14.         If FileUpload1.HasFile Then
  15.  
  16.             Dim MyFile As String = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName)
  17.             Dim attachmentFile As New Attachment(FileUpload1.PostedFile.InputStream, MyFile)
  18.             mail.Attachments.Add(attachmentFile)
  19.  
  20.         End If
  21.      
  22.         smtpserver.Send(mail)
  23.         Response.Write("<script language='JavaScript'>alert('Mensaje enviado correctamente...!!!');</script>")
  #2 (permalink)  
Antiguo 12/02/2014, 13:06
Avatar de alan_69niupi  
Fecha de Ingreso: junio-2011
Mensajes: 200
Antigüedad: 12 años, 11 meses
Puntos: 17
Respuesta: Error al enviar email

Para enviar correos por fuera necesitas algunas credenciales
yo tengo una archivo de configuración donde tengo mi información pero es lo mismo que necesitas
- from: [email protected]
- host: smtp.gmail.com
- password: pas
- port: 587
- credenciales: true


luego donde los necesito hago esto:


Cita:
public void EnviarCorreoElectronico(List<string> tos, string subject, string body, AlternateView av, List<Attachment> files, List<string> CCs)
{
try
{
string from = ConfigurationManager.AppSettings["from"];
int port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
string host = ConfigurationManager.AppSettings["host"];
string password = ConfigurationManager.AppSettings["password"];
bool activarSSL = Convert.ToBoolean(ConfigurationManager.AppSettings["credencials"]);
MailMessage msg = new MailMessage();

foreach (string to in tos)
msg.To.Add(new MailAddress(to));//se grega el destinatario

msg.From = new MailAddress(from);//se agrega el remitente
//msg.From = new MailAddress(from,"alias",System.Text.Encoding.UTF8 );
msg.Subject = subject;//se agrega el asunto
msg.SubjectEncoding = System.Text.Encoding.UTF8;

if (av != null)
{
msg.AlternateViews.Add(av);//se agrega el mensaje html con imagen
msg.IsBodyHtml = true;
}
else if (body != null)
{
msg.Body = body;//se agrega el mensaje
msg.BodyEncoding = System.Text.Encoding.Unicode;
msg.IsBodyHtml = false;
}

foreach (string cc in CCs)
msg.CC.Add(new MailAddress(cc));//se agregan los destinatarios con copias
if (files != null)//en dado caso de que el usuario no adjunte un documento
{
foreach (Attachment file in files)
msg.Attachments.Add(file);//se adjutan los archivos
}
SmtpClient client = new SmtpClient();
//client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(from, password);
//client.Port = port;
client.Host = host;
//client.EnableSsl = activarSSL; //Esto es para que vaya a través de SSL que es obligatorio con GMail

client.Send(msg); //Envia el correo
}
catch (System.Net.Mail.SmtpException ex)
{
throw new Exception("Error al enviar el correo:\n" + ex.Message);
}
catch (Exception ex)
{
throw new Exception("Error inesperado al enviar el correo:\n" + ex.Message);
}
}

las librerías que uso son estas:

Cita:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.IO;
using System.Web.Configuration;
using System.Configuration;
using System.Net.Mime;
como veras es C#, solo lo tienes que pasar a VB


Saludos!!!!!
  #3 (permalink)  
Antiguo 12/02/2014, 13:34
Avatar de drako_darpan  
Fecha de Ingreso: octubre-2008
Ubicación: Sinaloa
Mensajes: 617
Antigüedad: 15 años, 6 meses
Puntos: 58
Respuesta: Error al enviar email

Hola que tal, bueno yo lo hago asi:

Código C#:
Ver original
  1. bool valorRegresa = false;
  2.  
  3.             try
  4.             {
  5.                 MailMessage msj = new MailMessage();
  6.  
  7.                 msj.From = new MailAddress(sCuenta, "Titulo del Mensaje");
  8.                 msj.To.Add(sDestinatario);
  9.                 msj.Subject = "Asunto";
  10.  
  11.                 msj.Body = sCuerpoCorreo;
  12.  
  13.                 SmtpClient server = new SmtpClient(Ip del servidor desde el que se enviara el Email, Puerto de salida);
  14.                 server.UseDefaultCredentials = false;
  15.                 server.Credentials = new NetworkCredential(sCuenta, sPassword);
  16.                 server.Send(msj);
  17.  
  18.                 valorRegresa = true;
  19.             }
  20.             catch (Exception ex)
  21.             {
  22.                 MessageBox.Show("Ocurrio un error en el envio:\n" + ex.ToString(), sTitulo, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  23.                 valorRegresa = false;
  24.             }
  25.  
  26.             return valorRegresa;

En las cabeceras son:

Código C#:
Ver original
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.Mail;
  5. using System.Net;
  6. using System.Windows.Forms;

Recibe de parametros:

sDestinatario, sCuerpoCorreo, sCuenta, sPassword, sTitulo
  #4 (permalink)  
Antiguo 13/02/2014, 03:00
 
Fecha de Ingreso: noviembre-2013
Mensajes: 18
Antigüedad: 10 años, 6 meses
Puntos: 0
Respuesta: Error al enviar email

Gracias por vuestras respuestas, ya lo he conseguido, os adjunto la solución por si a alguien le sirve de ayuda.
El problema venia en esta linea.
smtpserver.Credentials = New Net.NetworkCredential.

yo estaba poniendo la cuenta desde donde se mandaba el correo y realmente hay que poner las credenciales de usuario dentro de la red.
smtpserver.Credentials = New Net.NetworkCredential(domino\usuario, password)

Saludos

Etiquetas: email, net
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 07:12.