How to attach a RAR file to an email in c#?

两盒软妹~` 提交于 2020-01-04 02:54:14

问题


I want to send an email that has multiple attachments using the following code but it doesn't work for RAR files. What is the problem? For every attachment I have a class that contains some properties of the attached file and its content:

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

The Send method is shown here:

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:


Please write your problem as short as possible! Long questions cause independent answers. I don't correct your code but you can attach a rar file using this simple code:

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


来源:https://stackoverflow.com/questions/22266089/how-to-attach-a-rar-file-to-an-email-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!