如何将RAR文件附加到c#中的电子邮件中?

时间:2014-03-08 06:42:14

标签: c# email attachment rar

我想使用以下代码发送包含多个附件的电子邮件,但它不适用于RAR文件。问题是什么? 对于每个附件,我都有一个类,其中包含附件的一些属性及其内容:

public class AttachmentFile
{
    [StringLength(200)]
    public string FileName { get; set; }
    [StringLength(15)]
    public string Extension { get; set; }
    [StringLength(100)]
    public string Signature { get; set; }
    public byte[] Content { get; set; }
    [StringLength(500)]
    public string FullPath { get; set; } 
}

Send方法如下所示:

public void Send(string from, List<string> recivers, string smtpHostName, string subject, string body, ICollection<AttachmentFile> attachmentFiles)
{
    var mailMessage = new MailMessage();
    foreach (var reciver in recivers)
    {
        mailMessage.To.Add(reciver);
    }

    mailMessage.Subject = subject;
    mailMessage.From = new MailAddress(@from);
    mailMessage.Body = RenderBody(body);
    if (attachmentFiles != null)
    {
        foreach (var attachmentFile in attachmentFiles)
        {
            var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Octet);
            mailMessage.Attachments.Add(new Attachment(new MemoryStream(attachmentFile.Content), "application/rar"));
        }
    }

    mailMessage.IsBodyHtml = true;
    mailMessage.SubjectEncoding = Encoding.UTF8;
    var smtp = new SmtpClient { Host = smtpHostName };
    smtp.Send(mailMessage);
}

1 个答案:

答案 0 :(得分:5)

请尽可能缩短您的问题!长问题会导致独立答案。 我没有更正你的代码,但你可以使用这个简单的代码附加一个rar文件:

var attachmentToSend = new Attachment(pathOfYourFile);
mailMessage.Attachments.Add(attachmentToSend);