Foros del Web

Foros del Web (http://www.forosdelweb.com/)
-   .NET (http://www.forosdelweb.com/f29/)
-   -   Hacer un SMTP directo (http://www.forosdelweb.com/f29/hacer-smtp-directo-264937/)

RootK 25/01/2005 15:08

Hacer un SMTP directo
 
1 Archivos Adjunto(s)
Hace tiempo encontré una página con una clase para hacer un SMTP de forma directa sin utilizar el que trae por default el framework, hace el mismo proceso de helo, mail, rcpt to, etc como si lo hicieras con telnet pero aqui es por código.

Aqui se los dejo:

Solo es cosa de crear un nuevo proyecto de tipo Class library y hacer un copy and paste, compilar e incluirlo en los proyectos que necesiten.

Por cierto para mandarlo a llamar sería:

(declarando el namespace SMTP :arriba:)

Cita:

SMTP.SmtpDirect.SmtpServer = txtSmtpServer.Text;
System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage();
msg.Body= txtBody.Text;
msg.From=txtFromEmail.Text;
msg.To=txtToEmail.Text;
msg.Subject =txtSubject.Text;

msg.Headers.Add("Reply-to",txtReplyTo.Text);

if(strAttachmentFile !=null && strAttachmentFile!="")
{
MailAttachment myAttachment = new MailAttachment(strAttachmentFile);


msg.Attachments.Add(myAttachment);

}

if(SMTP.SmtpDirect.Send(msg))
{
MessageBox.Show("Sent OK");
}
else
{
MessageBox.Show("Something BAD Happened!");
}
Es cosa de que cambien los textbox que usaba y los sustituyan por sus valores.

Cualquier duda me avisan.


Salu2

chcma 25/01/2005 15:37

SMTP.SmtpDirect.SmtpServer ¿?

Petdona mi ignorancia, pero eso, ¿Como lo declaraste?

RootK 26/01/2005 09:45

Es que lo tengo encerrado en mi namespace llamado SMTP y dentro tengo mi clase llamada SmtpDirect que a su vez tengo una propiedad de tipo static para c# ó shared para vb.net llamada SmtpServer

Y es por eso que se la paso sin necesidad de instanciar la clase.

Cita:

SMTP.SmtpDirect.SmtpServer = "mi servidor SMTP";
Namespace.Clase.propiedad = "mi servidor SMTP;
No se si ya pudiste ver el archivo que adjunté. :pensando: donde viene la clase SmtpDirect

Salu2

chcma 26/01/2005 09:59

Pues no tiu, si pues decirme como descargarlo, debe ser que últimamente estoy algo atontao.

RootK 26/01/2005 10:05

Creo que ustedes no pueden tener acceso para bajar el file, :serio: lo voy a checar, pero mientras aqui les dejo el code completo (copy and paste) :arriba:

Código PHP:

using System;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Web.Mail;
namespace SMTP
{
    
/// <summary>
    /// provides methods to send email via smtp direct to mail server
    /// </summary>
    
public class SmtpDirect
    
{
        
/// <summary>
        /// Get / Set the name of the SMTP mail server
        /// </summary>
        
public static string SmtpServer;
        private 
enum SMTPResponseint
        
{
            
CONNECT_SUCCESS 220,
            
GENERIC_SUCCESS 250,
            
DATA_SUCCESS    354,
            
QUIT_SUCCESS    221
            
        
}
        public static 
bool Send(MailMessage message)
        {
            
IPHostEntry IPhst Dns.Resolve(SmtpServer);
            
IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
            
Socket s = new Socket(endPt.AddressFamilySocketType.Stream,ProtocolType.Tcp);
            
s.Connect(endPt);
            
            if(!
Check_Response(sSMTPResponse.CONNECT_SUCCESS))
            {                
                
s.Close();
                return 
false;
            }
                
            
Senddata(sstring.Format("HELO {0}\r\n"Dns.GetHostName() ));
            if(!
Check_Response(sSMTPResponse.GENERIC_SUCCESS))
            {
                
s.Close();
                return 
false;
            }
                
            
Senddata(sstring.Format("MAIL From: {0}\r\n"message.From ));
            if(!
Check_Response(sSMTPResponse.GENERIC_SUCCESS))
            {
                
                
s.Close();
                return 
false;
            }
                
            
string _To message.To;
            
string[] Tos_To.Split(new char[] {';'});
            foreach (
string To in Tos)
            {
                
Senddata(sstring.Format("RCPT TO: {0}\r\n"To));
                if(!
Check_Response(sSMTPResponse.GENERIC_SUCCESS))
                {
                    
                    
s.Close();
                    return 
false;
                }
            }
                
            if(
message.Cc!=null)
            {
                
Tosmessage.Cc.Split(new char[] {';'});
                foreach (
string To in Tos)
                {
                    
Senddata(sstring.Format("RCPT TO: {0}\r\n"To));
                    if(!
Check_Response(sSMTPResponse.GENERIC_SUCCESS))
                    {                    
                        
s.Close();
                        return 
false;
                    }
                }
            }
                
            
StringBuilder Header=new StringBuilder();
            
Header.Append("From: " message.From "\r\n");
            
Tosmessage.To.Split(new char[] {';'});
            
Header.Append("To: ");
            for( 
int i=0iTos.Lengthi++)
            {
                
Header.Append"," "" );
                
Header.Append(Tos[i]);
            }
            
Header.Append("\r\n");
            if(
message.Cc!=null)
            {
                
Tosmessage.Cc.Split(new char[] {';'});
                
Header.Append("Cc: ");
                for( 
int i=0iTos.Lengthi++)
                {
                    
Header.Append"," "" );
                    
Header.Append(Tos[i]);
                }
                
Header.Append("\r\n");
            }
            
Header.Append"Date: " );
            
Header.Append(DateTime.Now.ToString("ddd, d M y H:m:s z" ));
            
Header.Append("\r\n");
            
Header.Append("Subject: " message.Subject"\r\n");
            
Header.Append"X-Mailer: SMTPDirect v1\r\n" );
            
string MsgBody message.Body;
            if(!
MsgBody.EndsWith("\r\n"))
                
MsgBody+="\r\n";
            if(
message.Attachments.Count>0)
            {
                
Header.Append"MIME-Version: 1.0\r\n" );
                
Header.Append"Content-Type: multipart/mixed; boundary=unique-boundary-1\r\n" );
                
Header.Append("\r\n");
                
Header.Append"This is a multi-part message in MIME format.\r\n" );
                
StringBuilder sb = new StringBuilder();
                
sb.Append("--unique-boundary-1\r\n");
                
sb.Append("Content-Type: text/plain\r\n");
                
sb.Append("Content-Transfer-Encoding: 7Bit\r\n");
                
sb.Append("\r\n");
                
sb.Append(MsgBody "\r\n");
                
sb.Append("\r\n");
                    
                foreach(
object o in message.Attachments)
                {
                    
MailAttachment a as MailAttachment;
                    
byte[] binaryData;
                    if(
a!=null)
                    {
                        
FileInfo f = new FileInfo(a.Filename);
                        
sb.Append("--unique-boundary-1\r\n");
                        
sb.Append("Content-Type: application/octet-stream; file=" f.Name "\r\n");
                        
sb.Append("Content-Transfer-Encoding: base64\r\n");
                        
sb.Append("Content-Disposition: attachment; filename=" f.Name "\r\n");
                        
sb.Append("\r\n");
                        
FileStream fs f.OpenRead();
                        
binaryData = new Byte[fs.Length];
                        
long bytesRead fs.Read(binaryData0, (int)fs.Length);
                        
fs.Close();
                        
string base64String System.Convert.ToBase64String(binaryData0,binaryData.Length);
                            
                        for(
int i=0ibase64String.Length ; )
                        {
                            
int nextchunk=100;
                            if(
base64String.Length - (nextchunk ) <0)
                                
nextchunk base64String.Length -i;
                            
sb.Append(base64String.Substring(inextchunk));
                            
sb.Append("\r\n");
                            
i+=nextchunk;
                            
                        }
                        
sb.Append("\r\n");
                        
                    }
                }
                
MsgBody=sb.ToString();
            }
                
            
Senddata(s, ("DATA\r\n"));
            if(!
Check_Response(sSMTPResponse.DATA_SUCCESS))
            {
                
                
s.Close();
                return 
false;
            }
            
Header.Append"\r\n" );
            
Header.AppendMsgBody );
            
Header.Append".\r\n" );
            
Header.Append"\r\n" );
            
Header.Append"\r\n" );
            
Senddata(sHeader.ToString());
            if(!
Check_Response(sSMTPResponse.GENERIC_SUCCESS ))
            {
                
                
s.Close();
                return 
false;
            }            
                
            
Senddata(s"QUIT\r\n");
            
Check_Response(sSMTPResponse.QUIT_SUCCESS );
            
s.Close();                
            return 
true;
        }
        private static 
void Senddata(Socket sstring msg)
        {
            
            
byte[] _msg Encoding.ASCII.GetBytes(msg);
            
s.Send(_msg 0_msg .LengthSocketFlags.None);
        }
        private static 
bool Check_Response(Socket sSMTPResponse response_expected )
        {
            
string sResponse;
            
int response;
            
byte[] bytes = new byte[1024];
            while (
s.Available==0)
            {
                
System.Threading.Thread.Sleep(100);
            }
                
            
s.Receive(bytes0s.AvailableSocketFlags.None);
            
sResponse Encoding.ASCII.GetString(bytes);
            
response Convert.ToInt32(sResponse.Substring(0,3));
            if(
response != (int)response_expected)
                return 
false;
            return 
true;
        }
    }



chcma 07/03/2005 09:08

Vale, este está muy bien, ¿Pero no tiene para autentificación, verdad?, es decir, para usar un SMTP privado.

xknown 07/03/2005 18:32

También tuve el mismo problema hace tiempo y encontré esto:
http://dotnetjunkies.com/WebLog/vbpu...les/23907.aspx

Saludos

chcma 08/03/2005 02:09

Jejejeje, está muy bien. Lástima que no indiquen alguna clase, similar a la que puso RootK, pero que también sirva para autentificación.

El problema de usar el MailMessage es que por ejemplo en Win98 no funciona, una pena hombre, "menos mal que .NET es multiplataforma", jejejeje.

Thanks xknown.

RootK 08/03/2005 08:58

Ya probaste con ésto tambien. ?

http://www.forosdelweb.com/s5fc89176...tml#post674283

RootK 08/03/2005 09:00

MM... aunque ahorita que estaba leyendo ese mismo post tu habías colocado ésto:

Cita:

Eso está muy bien, lástima que no sea multiplataforma, no vale ni pa Linux, ni pa Windows 98.

Hay que buscar otra solución. ¿No creen?
Aún así sigues con problemas..??? :pensando: , ya tienes instalado para win 98 el framework 1.1 ??

Salu2

chcma 08/03/2005 09:23

Si, pero en Win98, por ejemplo, no viene el componente COM CDO, que yo sepa. Vale, creo que se podría instalar, pero entonces, ya estariamos con instalaciones añadidas a la aplicación.

Creo que tu clase estaba muy bien, ya uqe una vez agregada al proyecto, el cliente tiene que olvidarse de instalar añadidos. Lo único malo, es que, por lo que vi, no tiene para autentificarse (Y creo que tampoco para añadir archivos, CREO, no mire bien). Y eso de no poder autentificarse, creo que es una carencia importante.


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

Desarrollado por vBulletin® Versión 3.8.7
Derechos de Autor ©2000 - 2026, Jelsoft Enterprises Ltd.