program story

HTML 이메일에 이미지 포함

inputbox 2020. 8. 18. 07:40
반응형

HTML 이메일에 이미지 포함


gif 이미지가 포함 된 멀티 파트 / 관련 html 이메일을 보내려고합니다. 이 이메일은 Oracle PL / SQL을 사용하여 생성됩니다. 이미지가 빨간색 X로 표시되면서 내 시도가 실패했습니다 (Outlook 2007 및 yahoo 메일).

나는 한동안 html 이메일을 보내 왔지만 이제 내 요구 사항은 이메일에서 여러 gif 이미지를 사용하는 것입니다. 웹 서버 중 하나에 저장하고 링크 만 할 수 있지만 많은 사용자 이메일 클라이언트가 자동으로 표시하지 않으며 각 이메일에 대해 설정을 변경하거나 수동으로 다운로드해야합니다.

그래서 제 생각은 이미지를 삽입하는 것입니다. 내 질문은 다음과 같습니다.

  1. 내가 여기서 뭘 잘못하고 있니?
  2. 임베딩 접근 방식이 올바른가요?
  3. 더 많은 이미지를 사용해야하는 경우 다른 옵션이 있습니까? 이미지는 일반적으로 메시지 컨텍스트에서 의미가없는 로고와 아이콘이므로 첨부 파일이 작동하지 않습니다. 또한 이메일의 일부 요소는 온라인 시스템에 대한 링크이므로 정적 PDF를 생성하고 첨부하는 것이 작동하지 않습니다 (내가 아는 한).

단편:

MIME-Version: 1.0
To: me@gmail.com
BCC: me@yahoo.com
From: email@yahoo.com
Subject: Test
Reply-To: email@yahoo.com
Content-Type: multipart/related; boundary="a1b2c3d4e3f2g1"

--a1b2c3d4e3f2g1

content-type: text/html;

    <html>
    <head><title>My title</title></head>
    <body>
    <div style="font-size:11pt;font-family:Calibri;">
    <p><IMG SRC="cid:my_logo" alt="Logo"></p>

... more html here ...

</div></body></html> 

--a1b2c3d4e3f2g1

Content-Type: image/gif;
Content-ID:<my_logo>
Content-Transfer-Encoding: base64
Content-Disposition: inline

[base64 image data here]

--a1b2c3d4e3f2g1--

감사합니다.

BTW : 예, html 자체에 이미지를 포함하고 (헤더 데이터 생성에 동일한 알고리즘 사용) Firefox / IE에서 이미지를 볼 수 있으므로 base64 데이터가 올바른지 확인했습니다.

또한 이것은 스팸이 아니며 이메일이 매일이를 기대하는 특정 클라이언트에게 전송된다는 점에 유의해야합니다. 콘텐츠는 광고가 아닌 데이터 기반입니다.


직접 삽입 해보세요. 이렇게하면 이메일의 여러 위치에 여러 이미지를 삽입 할 수 있습니다.

<img src="data:image/jpg;base64,{{base64-data-string here}}" />

이 게시물을 다른 사람들에게 유용하게 만들려면 : base64 데이터 문자열이없는 경우 이미지 파일에서 http://www.motobit.com/util/base64-decoder-encoder.asp 에서 쉽게 만들 수 있습니다. .

이메일 소스 코드는 다음과 같지만 그 경계가 무엇인지 정말로 말할 수 없습니다.

 To: email@email.de
 Subject: ...
 Content-Type: multipart/related;
 boundary="------------090303020209010600070908"

This is a multi-part message in MIME format.
--------------090303020209010600070908
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-15">
  </head>
  <body bgcolor="#ffffff" text="#000000">
    <img src="cid:part1.06090408.01060107" alt="">
  </body>
</html>

--------------090303020209010600070908
Content-Type: image/png;
 name="moz-screenshot.png"
Content-Transfer-Encoding: base64
Content-ID: <part1.06090408.01060107>
Content-Disposition: inline;
 filename="moz-screenshot.png"

[base64 image data here]

--------------090303020209010600070908--

// 편집하다 : 오, 나는 당신이 내 게시물의 첫 번째 코드 스 니펫을 삽입하여 thunderbird로 이메일을 작성하면 thunderbird가 내 게시물의 두 번째 코드와 거의 동일하게 보이도록 html 코드를 자동으로 변경합니다.


다른 솔루션은 이미지를 첨부 파일로 첨부 한 다음 cid를 사용하여 html 코드를 참조하는 것입니다.

HTML 코드 :

<html>
    <head>
    </head>
    <body>
        <img width=100 height=100 id="1" src="cid:Logo.jpg">
    </body>
</html>

C # 코드 :

EmailMessage email = new EmailMessage(service);
email.Subject = "Email with Image";
email.Body = new MessageBody(BodyType.HTML, html);
email.ToRecipients.Add("abc@xyz.com");
string file = @"C:\Users\acv\Pictures\Logo.jpg";
email.Attachments.AddFileAttachment("Logo.jpg", file);
email.Attachments[0].IsInline = true;
email.Attachments[0].ContentId = "Logo.jpg";
email.SendAndSaveCopy();

여기에 유용한 답변이 없으므로 솔루션을 제공하고 있습니다.

  1. The problem is that you are using multipart/related as the content type which is not good in this case. I am using multipart/mixed and inside it multipart/alternative (it works on most clients).

  2. The message structure should be as follows:

    [Headers]
    Content-type:multipart/mixed; boundary="boundary1"
    --boundary1
    Content-type:multipart/alternative; boundary="boundary2"
    --boundary2
    Content-Type: text/html; charset=ISO-8859-15
    Content-Transfer-Encoding: 7bit
    [HTML code with a href="cid:..."]
    
    --boundary2
    Content-Type: image/png;
    name="moz-screenshot.png"
    Content-Transfer-Encoding: base64
    Content-ID: <part1.06090408.01060107>
    Content-Disposition: inline; filename="moz-screenshot.png"
    [base64 image data here]
    
    --boundary2--
    --boundary1--
    

Then it will work


If it does not work, you may try one of these tools that convert the image to an HTML table (beware the size of your image though):


Using Base64 to embed images in html is awesome. Nonetheless, please notice that base64 strings can make your email size big.

Therefore,

1) If you have many images, uploading your images to a server and loading those images from the server can make your email size smaller. (You can get a lot of free services via Google)

2) If there are just a few images in your mail, using base64 strings is definitely an awesome option.

Besides the choices provided by existing answers, you can also use a command to generate a base64 string on linux:

base64 test.jpg

I know this is an old post, but the current answers dont address the fact that outlook and many other email providers dont support inline images or CID images. The most effective way to place images in emails is to host it online and place a link to it in the email. For small email lists a public dropbox works fine. This also keeps the email size down.


  1. You need 3 boundaries for inline images to be fully compliant.

  2. Everything goes inside the multipart/mixed.

  3. Then use the multipart/related to contain your multipart/alternative and your image attachment headers.

  4. Lastly, include your downloadable attachments inside the last boundary of multipart/mixed.


For those who couldnt get one of these solutions working: Send inline image in email Following the steps laid out in the solution offered by @T30 i was able to get my inline image to display without being blocked by outlook (previous methods it was blocked). If you are using exchange like we are then also when doing:

service = new ExchangeService(ExchangeVersion);
service.AutodiscoverUrl("email@domain.com");
SmtpClient smtp = new SmtpClient(service.Url.Host);

you will need to pass it your exchange service url host. Other than that following this solution should allow you to easily send embedded imgages.


It may be of interest that both Outlook and Outlook Express can generate these multipart image email formats, if you insert the image files using the Insert / Picture menu function.

Obviously the email type must be set to HTML (not plain text).

Any other method (e.g. drag/drop, or any command-line invocation) results in the image(s) being sent as an attachment.

If you then send such an email to yourself, you can see how it is formatted! :)

FWIW, I am looking for a standalone windows executable which does inline images from the command line mode, but there seem to be none. It's a path which many have gone up... One can do it with say Outlook Express, by passing it an appropriately formatted .eml file.


There's actually a very good blog post that lists pro's and cons of three different approaches to this problem by Martyn Davies. You can read it at https://sendgrid.com/blog/embedding-images-emails-facts/.

I'd like to add a fourth approach using CSS background images.

Add

<div id="myImage"></div>

to your e-mail body and a css class like:

#myImage {
    background-image:  url('data:image/png;base64,iVBOR...[some more encoding]...rkggg==');
    width: [the-actual-image-width];
    height: [the-actual-image-height];
}

The following is working code with two ways of achieving this:

using System;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            Method1();
            Method2();
        }

        public static void Method1()
        {
            Outlook.Application outlookApp = new Outlook.Application();
            Outlook.MailItem mailItem = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
            mailItem.Subject = "This is the subject";
            mailItem.To = "john@example.com";
            string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed

            var attachments = mailItem.Attachments;
            var attachment = attachments.Add(imageSrc);
            attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/jpeg");
            attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "myident"); // Image identifier found in the HTML code right after cid. Can be anything.
            mailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", true);

            // Set body format to HTML

            mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
            string msgHTMLBody = "<html><head></head><body>Hello,<br><br>This is a working example of embedding an image unsing C#:<br><br><img align=\"baseline\" border=\"1\" hspace=\"0\" src=\"cid:myident\" width=\"\" 600=\"\" hold=\" /> \"></img><br><br>Regards,<br>Tarik Hoshan</body></html>";
            mailItem.HTMLBody = msgHTMLBody;
            mailItem.Send();
        }

        public static void Method2()
        {

            // Create the Outlook application.
            Outlook.Application outlookApp = new Outlook.Application();

            Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);

            //Add an attachment.
            String attachmentDisplayName = "MyAttachment";

            // Attach the file to be embedded
            string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed

            Outlook.Attachment oAttach = mailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName);

            mailItem.Subject = "Sending an embedded image";

            string imageContentid = "someimage.jpg"; // Content ID can be anything. It is referenced in the HTML body

            oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid);

            mailItem.HTMLBody = String.Format(
                "<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>",
                imageContentid);

            // Add recipient
            Outlook.Recipient recipient = mailItem.Recipients.Add("john@example.com");
            recipient.Resolve();

            // Send.
            mailItem.Send();
        }
    }
}

If you are using Outlook to send a static image with hyperlink, an easy way would be to use Word.

  1. Open MS Word
  2. Copy the image onto a blank page
  3. Add hyperlink to the image (Ctrl + K)
  4. Copy the image to your email

참고URL : https://stackoverflow.com/questions/6706891/embedding-image-in-html-email

반응형