How to send email with attachment using MimeMessage in asp.net core web API?

て烟熏妆下的殇ゞ 提交于 2021-02-07 08:31:14

问题


I've tried with only simple text but i want to sent email with attachment.

    var emailMessage = new MimeMessage();
    emailMessage.From.Add(new MailboxAddress("Test","test@gmail.com"));
    emailMessage.To.Add(new MailboxAddress("Demo", "demo@gmail.com"));
    emailMessage.Subject = "Hello";
    emailMessage.Body = new TextPart("html") { Text = "Hi............" };

//I want Attachment here with body text..

    //Send Email.
    using (var client = new SmtpClient())
    {
            await client.ConnectAsync("smtp.gmail.com", 587, false);
            client.AuthenticationMechanisms.Remove("XOAUTH2");
            await client.AuthenticateAsync("uid", "pass");
            await client.SendAsync(emailMessage);
            await client.DisconnectAsync(true);
    }

回答1:


    var multipart = new Multipart("mixed");
    multipart.Add(new TextPart("html") { Text = "your body message"});

    // create an image attachment for the file located at path
    var attachment = new MimePart ("image", "gif") {
       ContentObject = new ContentObject (File.OpenRead (path), ContentEncoding.Default),
       ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
       ContentTransferEncoding = ContentEncoding.Base64,
       FileName = Path.GetFileName (path)
    };

    multipart.Add(attachment);
    emailMessage.Body = multipart;

For more detail, Please visit here



来源:https://stackoverflow.com/questions/41392811/how-to-send-email-with-attachment-using-mimemessage-in-asp-net-core-web-api

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