본문 바로가기
C#

.Net SMTP 메일 전송(Outlook)시 이미지 깨짐 현상 해결 방법

by csn123 2023. 12. 6.

이미지 src 링크가 특수한 페이지 (보안이 걸리는) 일 경우에 혹은 다른 특수한 이유로, 프로그래밍 방식으로 해당 메일을 재 전송시 이미지가 깨질수 있다.

이럴때 사용할 수 있는 방법이다.

대충 이미지를 미리 받아 아웃룩 내부 형식인 cid 로 링크를 바꿔주는듯 하다

 

 

MailMessage message = new MailMessage();
//LinkedResource (embedded image)
                var myResources = new List<LinkedResource>();
                int i = 0;
                if (doc.DocumentNode.SelectNodes("//img") != null && imgpath != "")
                {
                    foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//img"))
                    {
                        string imgnode = node.Attributes["src"].Value;
                        string logoId = Guid.NewGuid().ToString();
                        int node_count = doc.DocumentNode.SelectNodes("//img").Count;

                        image = @"이미지경로";
                        var webClient = new WebClient();
                        byte[] imageBytes = webClient.DownloadData(image);
                        MemoryStream ms = new MemoryStream(imageBytes);

                        LinkedResource logo = new LinkedResource(ms);
                        logo.ContentId = logoId;
                        logo.ContentType = new ContentType("image/png");
                        myResources.Add(logo);

                        node.Attributes["src"].Value = string.Format("cid:{0}", logo.ContentId);
                        mail_text = doc.DocumentNode.OuterHtml;
                        i++;
                    }
                }
                AlternateView htmlView =
                        AlternateView.CreateAlternateViewFromString(mail_text, Encoding.UTF8, "text/html");
                foreach (LinkedResource linkedResource in myResources)
                {
                    htmlView.LinkedResources.Add(linkedResource);
                }
                message.AlternateViews.Add(htmlView);
                #endregion

                SmtpClient client = new SmtpClient();
                client.Host = mailHost;
                client.Credentials = new System.Net.NetworkCredential(id, pass);

                client.Port = 포트번호;
                client.Send(message);

댓글