Send inline image in email

前端 未结 12 2201
夕颜
夕颜 2020-11-22 11:09

Having an issue sending an image via email as an embedded image in the body. The image file shows as an attachment which is ok but the inline image portion just shows as a r

12条回答
  •  青春惊慌失措
    2020-11-22 11:51

    We all have our preferred coding styles. This is what I did:

    var pictures = new[]
    {
        new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme", path = @"C:\Pictures\JustMe.jpg" },
        new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme-bw", path = @"C:\Pictures\JustMe-BW.jpg" }
    }.ToList();
    
    var content = $@"
    
    
    

    {DateTime.Now:ffffdd, MMMM d, yyyy h:mm:ss tt}

    Some pictures

    Color Picture

    Black and White Picture

    Color Picture repeated

    "; // Update content with picture guid pictures.ForEach(p => content = content.Replace($"{{{p.tag}}}", $"{p.id}")); // Create Alternate View var view = AlternateView.CreateAlternateViewFromString(content, Encoding.UTF8, MediaTypeNames.Text.Html); // Add the resources pictures.ForEach(p => view.LinkedResources.Add(new LinkedResource(p.path, p.type) { ContentId = p.id.ToString() })); using (var client = new SmtpClient()) // Set properties as needed or use config file using (MailMessage message = new MailMessage() { IsBodyHtml = true, BodyEncoding = Encoding.UTF8, Subject = "Picture Email", SubjectEncoding = Encoding.UTF8, }) { message.AlternateViews.Add(view); message.From = new MailAddress("me@me.com"); message.To.Add(new MailAddress("you@you.com")); client.Send(message); }

提交回复
热议问题