2010-05-13 15 views
80

Ho un'applicazione C# che invia via e-mail i rapporti del foglio di calcolo Excel tramite un server Exchange 2007 tramite SMTP. Questi arrivano bene per gli utenti di Outlook, ma per gli utenti di Thunderbird e Blackberry gli allegati sono stati rinominati come "Parte 1.2".Invio di e-mail con allegati da C#, gli allegati arrivano come parte 1.2 in Thunderbird

Ho trovato questo article che descrive il problema, ma non sembra darmi una soluzione. Non ho il controllo del server Exchange, quindi non posso apportare modifiche lì. C'è qualcosa che posso fare sulla fine del C#? Ho provato a usare nomi brevi di file e codifica HTML per il corpo, ma nessuno dei due ha fatto la differenza.

La mia mail di invio codice è semplicemente questo:

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); 
} 

Grazie per qualsiasi aiuto.

+0

Avete cercato di definire/modificare 'Allegato .Nome' proprietà? – Alex

+0

No, non ho - "Ottiene o imposta il valore del nome del tipo di contenuto MIME", hai un suggerimento su quale valore provare? Grazie. – Jon

+0

Il 'Nome' viene visualizzato come nome dell'allegato quando viene ricevuta l'e-mail con l'allegato. Quindi puoi provare qualsiasi valore. – Alex

risposta

71

Compilare esplicitamente i campi ContentDisposition ha fatto il trucco.

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

Perché non dovresti usare un oggetto 'FileInfo' per ottenere le proprietà' CreationTime', 'LastWriteTime' e' LastAccessTime'? Ne stai creando uno per ottenere comunque la proprietà 'Length'. – Krumia

63

Codice semplice per inviare e-mail con allegato.

fonte: 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

È necessario eseguire il wrapping di MailMessage e SmtpClient con le istruzioni using per assicurarsi che siano disposte correttamente – Andrew

+1

@Andrew - come faccio? – Steam

+0

Ho provato questo codice e ho ricevuto l'errore mostrato in questo post: http://stackoverflow.com/questions/20845469/finding-the-exact-cause-for-the-exception-system-net-sockets-socketexception – Steam

4

Completano la soluzione di Ranadheer, utilizzando Server.MapPath per individuare il file

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

Da dove proviene' Server.MapPath' e quando dovrebbe essere usato? – Kimmax

0

Prova questo:

private void btnAtt_Click(object sender, EventArgs e) { 

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

    MyMsg.Attachments.Add(myFile); 


} 
6

Ecco un semplice mail che invia il codice con allegato

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); 
} 

Leggi tutto 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

fratelli ciao ho fatto un breve codice per fare che mi piacerebbe condividere con voi

qui il codice principale

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); 
} 

} 

nel tuo pulsante fai cose del genere
è possibile aggiungere i filtri si jpg o pdf e più .. questo è solo un esempio

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 che se utile di dare un feedback grazie