c# smtpclient를 사용하여 이미지를 인라인으로 메일을 보냅니다
-
06-07-2019 - |
문제
smtpclient ()는 메일에 첨부 파일을 추가 할 수 있지만 메일을 첨부하는 대신 메일이 열릴 때 이미지가 표시되면 어떻게해야합니까?
내가 기억 하듯이, 약 4 줄의 코드로 수행 할 수는 있지만 MSDN 사이트에서 어떻게 찾을 수 없으며 어떻게 찾을 수 없습니까?
편집 : 나는 웹 사이트 나 아무것도 사용하지 않고 IP 주소도 사용하지 않습니다. 이미지는 하드 드라이브에 있습니다. 보내지면 우편물의 일부가되어야합니다. 그래서, 나는 태그를 사용하고 싶을 것 같지만 ... 내 컴퓨터가 방송되지 않기 때문에 너무 확실하지 않습니다.
해결책
자주 언급되는 한 가지 솔루션은 이미지를 다음으로 추가하는 것입니다. Attachment
우편물에 다음 HTML MailBody에서 cid:
참조.
그러나 당신이 사용하는 경우 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);
}
노트: 이 솔루션은 an을 추가합니다 AlternateView
너의 ~에게 MailMessage
유형의 text/html
. 완전성을 위해서도 추가해야합니다 AlternateView
유형의 text/plain
, 비 HTML 메일 클라이언트를위한 일반 텍스트 버전을 포함합니다.
다른 팁
HTML 이메일과 이미지는 첨부 파일이므로 콘텐츠 ID (IE)에서 이미지를 참조하는 경우입니다.
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 줄의 코드를 말할 때 이것?
System.Net.Mail.Attachment inline = new System.Net.Mail.Attachment(@"imagepath\filename.png");
inline.ContentDisposition.Inline = true;
Base64 문자열에서 이미지를 변환하는 것은 어떻습니까? afaik 이것은 우편 본문에 쉽게 내장 될 수 있습니다.
구경하다 여기.
이미 게시 된 솔루션은 내가 찾은 최고입니다. 예를 들어 여러 이미지가있는 경우 완료하겠습니다.
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);
}
}
});
알 수 있듯이 이미지 이름 배열이 있음을 알 수 있듯이 이미지는 동일한 출력 폴더를 가리키기 때문에 동일한 폴더에있는 것이 중요합니다.
마지막으로 이메일이 비동기로 전송되므로 사용자가 전송 될 때까지 기다릴 필요가 없습니다.
메일을 열면 클라이언트에 이미지를 만드는 프로세스가 클라이언트 기능입니다. 클라이언트가 이미지 렌더링 방법을 알고 있고 이미지 컨텐츠를 차단하지 않은 한 바로 열립니다. 이미지 MIME 첨부 파일 유형을 올바르게 지정한 한 클라이언트에 이메일을 보내기 위해 이메일을 보내는 동안 특별한 일을 할 필요가 없습니다.