发送带有附件的电子邮件

发送带有附件的电子邮件

我只尝试了简单的文本,但是我想发送带有附件的电子邮件。

    var emailMessage = new MimeMessage();
    emailMessage.From.Add(new MailboxAddress("Test","[email protected]"));
    emailMessage.To.Add(new MailboxAddress("Demo", "[email protected]"));
    emailMessage.Subject = "Hello";
    emailMessage.Body = new TextPart("html") { Text = "Hi............" };


//我要在此处附上正文。

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

最佳答案

    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;


有关更多详细信息,请访问here

07-25 23:58