SmtpClientを使用してインラインで画像を含むメールを送信するC#

StackOverflow https://stackoverflow.com/questions/1212838

  •  06-07-2019
  •  | 
  •  

質問

SmtpClient()を使用すると、メールに添付ファイルを追加できますが、メールを添付する代わりに、メールを開いたときに画像を表示したい場合はどうなりますか?

覚えているように、約4行のコードで実行できますが、MSDNサイトでそれを見つけることができません。

編集:ウェブサイトなど何も使用しておらず、IPアドレスも使用していません。画像はハードドライブにあります。送信されると、メールの一部になります。だから、タグを使いたいと思うかもしれません...しかし、私のコンピューターはブロードキャストしていないので、私はあまり確信がありません。

役に立ちましたか?

解決

よく言及される解決策の1つは、イメージを Attachment としてメールに追加し、 cid:参照を使用してHTMLメールボディで参照することです。

ただし、代わりに LinkedResources コレクションを使用する場合、インライン画像は引き続き正常に表示されますが、メールへの追加の添付ファイルとして表示されません。 それが私たちが実現したいことです、それが私がここで行うことです:

using (var client = new SmtpClient())
{
    MailMessage newMail = new MailMessage();
    newMail.To.Add(new MailAddress("you@your.address"));
    newMail.Subject = "Test Subject";
    newMail.IsBodyHtml = true;

    var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.png"), "image/png");
    inlineLogo.ContentId = Guid.NewGuid().ToString();

    string body = string.Format(@"
            <p>Lorum Ipsum Blah Blah</p>
            <img src=""cid:{0}"" />
            <p>Lorum Ipsum Blah Blah</p>
        ", inlineLogo.ContentId);

    var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
    view.LinkedResources.Add(inlineLogo);
    newMail.AlternateViews.Add(view);

    client.Send(newMail);
}

注:このソリューションは、 text / html タイプの MailMessage AlternateView を追加します。完全を期すために、 text / plain タイプの AlternateView を追加する必要があります。これには、非HTMLメールクライアント用の電子メールのプレーンテキストバージョンが含まれます。

他のヒント

HTMLメールと画像は添付ファイルであるため、コンテンツIDで画像を参照するだけです。つまり、

    Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(txtImagePath.Text)
    Dim RGen As Random = New Random()
    A.ContentId = RGen.Next(100000, 9999999).ToString()
    EM.Body = "<img src='cid:" + A.ContentId +"'>" 

ここに包括的な例があるようです:メールを送信インライン画像付き

4行のコードを言うとき、 this を参照していますか?

System.Net.Mail.Attachment inline = new System.Net.Mail.Attachment(@"imagepath\filename.png");
inline.ContentDisposition.Inline = true;

Base64文字列の画像の変換はどうですか?私の知る限り、これはメール本文に簡単に埋め込むことができます。

こちら

既に投稿されたソリューションは、私が見つけた最高のものです。たとえば、複数の画像がある場合にそれを完成させます。

        string startupPath = AppDomain.CurrentDomain.RelativeSearchPath;
        string path = Path.Combine(startupPath, "HtmlTemplates", "NotifyTemplate.html");
        string body = File.ReadAllText(path);

        //General tags replacement.
        body = body.Replace("[NOMBRE_COMPLETO]", request.ToName);
        body = body.Replace("[ASUNTO_MENSAJE]", request.Subject);

        //Image List Used to replace into the template.
        string[] imagesList = { "h1.gif", "left.gif", "right.gif", "tw.gif", "fb.gif" };

        //Here we create link resources one for each image. 
        //Also the MIME type is obtained from the image name and not hardcoded.
        List<LinkedResource> imgResourceList = new List<LinkedResource>();
        foreach (var img in imagesList)
        {
            string imagePath = Path.Combine(startupPath, "Images", img);
            var image = new LinkedResource(imagePath, "image/" + img.Split('.')[1]);
            image.ContentId = Guid.NewGuid().ToString();
            image.ContentType.Name = img;
            imgResourceList.Add(image);
            body = body.Replace("{" + Array.IndexOf(imagesList, img) + "}", image.ContentId);
        }

        //Altern view for managing images and html text is created.
        var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
        //You need to add one by one each link resource to the created view
        foreach (var imgResorce in imgResourceList)
        {
            view.LinkedResources.Add(imgResorce);
        }

        ThreadPool.QueueUserWorkItem(o =>
        {
            using (SmtpClient smtpClient = new SmtpClient(servidor, Puerto))
            {
                smtpClient.EnableSsl = true;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.Timeout = 50000;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new System.Net.NetworkCredential()
                {
                    UserName = UMail,
                    Password = password
                };
                using (MailMessage mailMessage = new MailMessage())
                {
                    mailMessage.IsBodyHtml = true;
                    mailMessage.From = new MailAddress(UMail);
                    mailMessage.To.Add(request.ToEmail);
                    mailMessage.Subject = "[NAPNYL] " + request.Subject;
                    mailMessage.AlternateViews.Add(view);
                    smtpClient.Send(mailMessage);
                }
            }
        });

画像名の配列があることがわかるように、画像は同じ出力フォルダーを指しているため、画像が同じフォルダーにあることが重要です。

最終的にメールは非同期で送信されるため、ユーザーは送信を待つ必要がありません。

メールが開かれたときにクライアントに画像を表示するプロセスは、クライアント機能です。クライアントが画像のレンダリング方法を知っている限り&amp;画像コンテンツをブロックしていないため、すぐに開きます。画像のMIME添付ファイルの種類を正しく指定している限り、メールを送信する際に特別なことをしてクライアントで開く必要はありません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top