从C#发送带有附件的电子邮件,附件在Thunderbird中作为第1.2部分送达

从C#发送带有附件的电子邮件,附件在Thunderbird中作为第1.2部分送达,c#,email,smtp,attachment,C#,Email,Smtp,Attachment,我有一个C#应用程序,它使用SMTP通过Exchange2007服务器发送Excel电子表格报告。这些附件对于Outlook用户来说很好,但是对于Thunderbird和Blackberry用户来说,附件已经被重命名为“Part1.2” 我发现这个描述了问题,但似乎没有给我一个解决办法。我无法控制Exchange服务器,因此无法在那里进行更改。在C#end有什么我能做的吗?我曾经尝试过在正文中使用短文件名和HTML编码,但都没有效果 我的邮件发送代码如下: public static void

我有一个C#应用程序,它使用SMTP通过Exchange2007服务器发送Excel电子表格报告。这些附件对于Outlook用户来说很好,但是对于Thunderbird和Blackberry用户来说,附件已经被重命名为“Part1.2”

我发现这个描述了问题,但似乎没有给我一个解决办法。我无法控制Exchange服务器,因此无法在那里进行更改。在C#end有什么我能做的吗?我曾经尝试过在正文中使用短文件名和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);
}

感谢您的帮助。

显式填写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;

发送带有附件的电子邮件的简单代码

资料来源:


使用Server.MapPath查找文件,完成Ranadheer的解决方案

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

private void btnAtt_Click(object sender, EventArgs e) {

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

    MyMsg.Attachments.Add(myFile);


}

下面是一个带有附件的简单邮件发送代码

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

阅读更多内容

我制作了一个简短的代码来实现这一点,我想与大家分享

以下是主要代码:

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文件等。。这只是一个例子


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

最初,我尝试使用nugent软件包管理器提供的EASendMail,但后来才意识到这是一个付费版本,试用期为30天。除非你打算买下它,否则不要浪费时间。我注意到使用EASendMail程序运行得快得多,但对我来说,免费胜过了快速


只值我2美分。

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

使用Outlook=Microsoft.Office.Interop.Outlook;//如果以后要使用生成代理,请从本地或nuget引用Microsoft.Office.Interop.Outlook

 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."
                    };
                }

您是否尝试过定义/更改附件.Name属性?不,我没有-“获取或设置MIME内容类型名称值”,您是否有建议尝试使用什么值?谢谢。收到带有附件的电子邮件时,
名称
将显示为附件的名称。因此,您可以尝试任何值。您应该使用using语句包装MailMessage和SmtpClient,以确保它们已被释放correctly@Andrew-我该怎么做?我尝试了这段代码,在这篇文章中显示了一个错误-@Steam你可以这样做
使用(SmtpClient SmtpServer=new SmtpClient(“smtp.gmail.com”){//code在这里使用(MailMessage mail=new MailMessage()){//code在这里运行}
为什么不使用
FileInfo
对象来获取
CreationTime
LastWriteTime
LastAccessTime
属性?您正在创建一个对象来获取
长度
属性。别忘了attachment.Dispose()或者此文件仍处于锁定状态,您将无法在其上写入数据。
Server.MapPath
从何而来,何时使用?编写此文件的人可能是ASP.NET程序员,我认为从相对文件名中给出完整的限定文件名会有所帮助。原始问题没有提到ASP.NET;您可以在那里放置对文件名的完整引用。
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);
  }

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

}
}
 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."
                    };
                }