使用C#发送带附件的电子邮件,在Thunderbird中附件会作为1.2部分到达。

123
我有一个C#应用程序,可以通过SMTP使用Exchange 2007服务器向Excel电子表格报告发送电子邮件。对于Outlook用户,这些电子邮件没有问题,但是对于Thunderbird和Blackberry用户,附件已更名为“Part 1.2”。
我找到了这篇文章, 描述了这个问题,但似乎没有给我提供解决方法。我无法控制Exchange服务器,因此无法在那里进行更改。在C#方面我能做什么吗?我已尝试使用短文件名和HTML编码正文,但都没有改变。
我的邮件发送代码只是这样的:
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);
}

感谢任何帮助。


你尝试定义/更改过Attachment.Name属性吗? - Oleks
没有,我没有尝试“获取或设置MIME内容类型名称值”,你有什么建议要尝试哪个值吗?谢谢。 - Jon
当带有附件的电子邮件被接收时,“名称”将显示为附件的名称。因此,您可以尝试任何值。 - Oleks
9个回答

128

发送带附件的邮件的简单代码。

来源: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 mail@gmail.com");
    mail.To.Add("to_mail@gmail.com");
    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 mail@gmail.com", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}

22
为确保正确处理对象的释放,您应使用"using"语句对MailMessage和SmtpClient进行封装。 - Andrew
1
@Andrew - 我该怎么做? - Steam
我尝试了这段代码,但是我得到了这篇文章中显示的错误 - http://stackoverflow.com/questions/20845469/finding-the-exact-cause-for-the-exception-system-net-sockets-socketexception - Steam
2
@Steam你可以这样做:using(SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com")) { //代码放在这里 using(MailMessage mail = new MailMessage()){ //代码放在这里 } } - Shamseer K

101

明确填写ContentDisposition字段就解决了问题。

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

顺便说一下,在 Gmail 的情况下,你可能会遇到一些关于 SSL 安全性甚至端口的异常情况!

smtpClient.EnableSsl = true;
smtpClient.Port = 587;

2
为什么不使用 FileInfo 对象来获取 CreationTimeLastWriteTimeLastAccessTime 属性呢?反正你已经创建了一个对象来获取 Length 属性了。 - sampathsris
1
不要忘记使用attachment.Dispose(),否则该文件将保持锁定状态,您将无法在其上写入数据。 - Pau Dominguez

7
这里是一个带附件的简单邮件发送代码。
try  
{  
    SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);  
    mailServer.EnableSsl = true;  

    mailServer.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypassword");  

    string from = "myemail@gmail.com";  
    string to = "reciever@gmail.com";  
    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);  
}

阅读更多 使用 C# 发送带附件的电子邮件


5

使用Server.MapPath来定位文件,完成Ranadheer的解决方案。

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

Server.MapPath 是什么,何时应该使用它? - Kimmax
写这篇文章的人可能是一个ASP.NET程序员,我认为从相对文件名中给出完全限定的文件名只是有帮助的。原始问题没有提到ASP.NET;你可以在那里放一个完整的文件名引用。 - NealWalters

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

1
我已经写了一个简短的代码来完成这个任务,我想与你分享。

以下是主要代码:
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);
  }

}

在您的按钮中执行以下操作: 您可以添加您的jpg或pdf文件等更多内容..这只是一个示例。
using (OpenFileDialog attachement = new OpenFileDialog()
{
  Filter = "Exel Client|*.png",
  ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
  Send("yourmail@gmail.com", "gmail_password", 
       "tomail@gmail.com", "just smile ", "mail with attachement",
       "smtp.gmail.com", 587, attachement.FileName);

}
}

0

试试这个:

private void btnAtt_Click(object sender, EventArgs e) {

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

    MyMsg.Attachments.Add(myFile);


}

0

我尝试了Ranadheer Reddy(上面)提供的代码,效果非常好。如果您正在使用受限制的服务器的公司计算机,则可能需要将SMTP端口更改为25,并且将用户名和密码留空,因为它们将由管理员自动填充。

最初,我尝试使用nugent包管理器中的EASendMail,只是意识到它是一个付费版本,有30天的试用期。除非您打算购买它,否则不要浪费时间。我注意到使用EASendMail运行程序速度更快,但对我来说,免费胜过快速。

这只是我的个人看法。


0

使用此方法,您可以在电子邮件服务下将任何电子邮件正文和附件附加到Microsoft Outlook

使用Outlook = Microsoft.Office.Interop.Outlook; // 引用 Microsoft.Office.Interop.Outlook 从本地或NuGet中引用,如果您稍后将使用构建代理

 try {
                    var officeType = Type.GetTypeFromProgID("Outlook.Application");
    
                    if(officeType == null) {//outlook is not installed
                        return new PdfErrorResponse {
                            ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
                        };
                    } else {
                        // Outlook is installed.    
                        // Continue your work.
                        Outlook.Application objApp = new Outlook.Application();
                        Outlook.MailItem mail = null;
                        mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
                        //The CreateItem method returns an object which has to be typecast to MailItem 
                        //before using it.
                        mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
                        //The parameters are explained below
                        mail.To = recipientEmailAddress;
                        //mail.CC = "con@def.com";//All the mail lists have to be separated by the ';'
    
                        //To send email:
                        //mail.Send();
                        //To show email window
                        await Task.Run(() => mail.Display());
                    }
    
                } catch(System.Exception) {
                    return new PdfErrorResponse {
                        ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
                    };
                }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接