2010-05-13 34 views
80

Tengo una aplicación C# que envía por correo electrónico informes de hojas de cálculo Excel a través de un servidor de Exchange 2007 usando SMTP. Estos llegan bien para los usuarios de Outlook, pero para los usuarios de Thunderbird y Blackberry los archivos adjuntos se han renombrado como "Parte 1.2".Enviando correos electrónicos con archivos adjuntos desde C#, los archivos adjuntos llegan como parte 1.2 en Thunderbird

Encontré este article que describe el problema, pero no parece darme una solución. No tengo control del servidor de Exchange, así que no puedo hacer cambios allí. ¿Hay algo que pueda hacer en el extremo de C#? Intenté usar nombres de archivo cortos y codificación HTML para el cuerpo, pero ninguno hizo la diferencia.

Mi correo de envío de código es simplemente esto:

public static void SendMail(string recipient, string subject, string body, string attachmentFilename) 
{ 
    SmtpClient smtpClient = new SmtpClient(); 
    NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password); 
    MailMessage message = new MailMessage(); 
    MailAddress fromAddress = new MailAddress(MailConst.Username); 

    // setup up the host, increase the timeout to 5 minutes 
    smtpClient.Host = MailConst.SmtpServer; 
    smtpClient.UseDefaultCredentials = false; 
    smtpClient.Credentials = basicCredential; 
    smtpClient.Timeout = (60 * 5 * 1000); 

    message.From = fromAddress; 
    message.Subject = subject; 
    message.IsBodyHtml = false; 
    message.Body = body; 
    message.To.Add(recipient); 

    if (attachmentFilename != null) 
     message.Attachments.Add(new Attachment(attachmentFilename)); 

    smtpClient.Send(message); 
} 

Gracias por cualquier ayuda.

+0

¿Usted ha intentado definir/cambiar 'adjuntos ¿Propiedad de .Name? – Alex

+0

No, no he - "Obtiene o establece el valor de nombre de tipo de contenido MIME", ¿tiene alguna sugerencia sobre qué valor probar? Gracias. – Jon

+0

El 'Nombre' se muestra como el nombre del archivo adjunto cuando se recibe el correo electrónico con el archivo adjunto. Entonces puedes probar cualquier valor. – Alex

Respuesta

71

Rellenar explícitamente los campos de ContentDisposition hizo el truco.

if (attachmentFilename != null) 
{ 
    Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet); 
    ContentDisposition disposition = attachment.ContentDisposition; 
    disposition.CreationDate = File.GetCreationTime(attachmentFilename); 
    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename); 
    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename); 
    disposition.FileName = Path.GetFileName(attachmentFilename); 
    disposition.Size = new FileInfo(attachmentFilename).Length; 
    disposition.DispositionType = DispositionTypeNames.Attachment; 
    message.Attachments.Add(attachment);     
} 
+0

¿Por qué no usaría un objeto 'FileInfo' para obtener las propiedades' CreationTime', 'LastWriteTime', y' LastAccessTime'? Usted está creando uno para obtener la propiedad 'Longitud' de todos modos. – Krumia

63

Código simple para enviar correos electrónicos con adjunto.

fuente: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html

using System.Net; 
using System.Net.Mail; 

public void email_send() 
{ 
    MailMessage mail = new MailMessage(); 
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 
    mail.From = new MailAddress("your [email protected]"); 
    mail.To.Add("[email protected]"); 
    mail.Subject = "Test Mail - 1"; 
    mail.Body = "mail with attachment"; 

    System.Net.Mail.Attachment attachment; 
    attachment = new System.Net.Mail.Attachment("c:/textfile.txt"); 
    mail.Attachments.Add(attachment); 

    SmtpServer.Port = 587; 
    SmtpServer.Credentials = new System.Net.NetworkCredential("your [email protected]", "your password"); 
    SmtpServer.EnableSsl = true; 

    SmtpServer.Send(mail); 

} 
+10

Debería envolver MailMessage y SmtpClient con instrucciones de uso para asegurarse de que están dispuestas correctamente – Andrew

+1

@Andrew: ¿cómo hago eso? – Steam

+0

Intenté este código y obtuve el error que se muestra en esta publicación - http://stackoverflow.com/questions/20845469/finding-the-exact-cause-for-the-exception-system-net-sockets-socketexception – Steam

4

Completando la solución de Ranadheer, utilizando Server.MapPath para localizar el archivo

System.Net.Mail.Attachment attachment; 
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf")); 
mail.Attachments.Add(attachment); 
+0

¿De dónde viene' Server.MapPath' y cuándo debería usarse? – Kimmax

0

Prueba esto:

private void btnAtt_Click(object sender, EventArgs e) { 

    openFileDialog1.ShowDialog(); 
    Attachment myFile = new Attachment(openFileDialog1.FileName); 

    MyMsg.Attachments.Add(myFile); 


} 
6

Aquí es una código simple de envío de correo con el archivo adjunto

try 
{ 
    SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587); 
    mailServer.EnableSsl = true; 

    mailServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword"); 

    string from = "[email protected]"; 
    string to = "[email protected]"; 
    MailMessage msg = new MailMessage(from, to); 
    msg.Subject = "Enter the subject here"; 
    msg.Body = "The message goes here."; 
    msg.Attachments.Add(new Attachment("D:\\myfile.txt")); 
    mailServer.Send(msg); 
} 
catch (Exception ex) 
{ 
    Console.WriteLine("Unable to send email. Error : " + ex); 
} 

Leer más Sending emails with attachment in C#

1
private void btnSent_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     MailMessage mail = new MailMessage(); 
     SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 

     mail.From = new MailAddress(txtAcc.Text); 
     mail.To.Add(txtToAdd.Text); 
     mail.Subject = txtSub.Text; 
     mail.Body = txtContent.Text; 
     System.Net.Mail.Attachment attachment; 
     attachment = new System.Net.Mail.Attachment(txtAttachment.Text); 
     mail.Attachments.Add(attachment); 

     SmtpServer.Port = 587; 
     SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text); 

     SmtpServer.EnableSsl = true; 

     SmtpServer.Send(mail); 
     MessageBox.Show("mail send"); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    MailMessage mail = new MailMessage(); 
    openFileDialog1.ShowDialog(); 
    System.Net.Mail.Attachment attachment; 
    attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName); 
    mail.Attachments.Add(attachment); 
    txtAttachment.Text =Convert.ToString (openFileDialog1.FileName); 
} 
0

hermanos hola hice un código corto para hacer que me gustaría compartir con ustedes

aquí el código principal

public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file) 
{ 

MailMessage email = new MailMessage(); 
email.From = new MailAddress(from); 
email.To.Add(to); 
email.Subject = subject; 
email.Body = Message; 
SmtpClient smtp = new SmtpClient(host, port); 
smtp.UseDefaultCredentials = false; 
NetworkCredential nc = new NetworkCredential(from, password); 
smtp.Credentials = nc; 
smtp.EnableSsl = true; 
email.IsBodyHtml = true; 
email.Priority = MailPriority.Normal; 
email.BodyEncoding = Encoding.UTF8; 

if (file.Length > 0) 
{ 
Attachment attachment; 
attachment = new Attachment(file); 
email.Attachments.Add(attachment); 
} 

// smtp.Send(email); 
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack); 
string userstate = "sending ..."; 
smtp.SendAsync(email, userstate); 
} 

private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) { 
string result = ""; 
if (e.Cancelled) 
{ 

MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information); 
} 
else if (e.Error != null) 
{ 
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); 
} 
else { 
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); 
} 

} 

en su botón hacer cosas como esta
puede agregar que los filtros jpg o pdf y más .. esto es sólo un ejemplo

using (OpenFileDialog attachement = new OpenFileDialog() 
{ 
Filter = "Exel Client|*.png", 
ValidateNames = true 
}) 
{ 
if (attachement.ShowDialog() == DialogResult.OK) 
{ 
Send("[email protected]", "gmail_password", "[email protected]", "just smile ", "mail with attachement", "smtp.gmail.com", 587, attachement.FileName); 

} 
} 

voto que si atento de dar una retroalimentación gracias

Cuestiones relacionadas