要在电子邮件中嵌入图像,您不需要使用System.Drawing
. 您只需要将图像内容放入您的电子邮件中。这是我的示例:
public static class Function1
{
[FunctionName("Function1")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]HttpRequest req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
// To simplify the test, I diredtly get the image bytes from base64encoded string.
string base64String = "/9j/4gIcSUNDX1BST0ZJT********NjN8uMCgsR4lzsgB7Q6gAggunL9Lgw88jkGAPOlL3kk2gggud11//Z";
byte[] jpg = Convert.FromBase64String(base64String);
using (MemoryStream stream = new MemoryStream(jpg))
{
LinkedResource res = new LinkedResource(stream, MediaTypeNames.Image.Jpeg);
res.ContentId = Guid.NewGuid().ToString();
string htmlBody = $"<html><body><h1>Picture</h1><br><img src=\"cid:{res.ContentId}\" /></body></html>";
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, Encoding.UTF8, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(res);
MailMessage message = new MailMessage(new MailAddress("jack@hanxia.onmicrosoft.com"), new MailAddress("jialinjun@gmail.com"));
message.Subject = "Send email with imgae";
message.AlternateViews.Add(alternateView);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.office365.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("jack@hanxia.onmicrosoft.com", "***the_password***");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
return (ActionResult)new OkObjectResult($"{htmlBody}");
}
}
}
调用该函数后,我可以收到一封新电子邮件jialinjun@gmail.com
: