업데이트 된 답변 :
SmtpClient이 답변에 사용 된 클래스에 대한 설명서는 이제 'Obsolete ( "SmtpClient 및 해당 유형의 네트워크가 잘못 설계되었습니다. https://github.com/jstedfast/MailKit 및 https : // github 를 사용하는 것이 좋습니다 . .com / jstedfast / MimeKit 대신 ") '.
출처 : https://www.infoq.com/news/2017/04/MailKit-MimeKit-Official
원래 답변 :
MailDefinition 클래스를 사용하는 것은 잘못된 접근 방식입니다. 예, 편리하지만 원시적이며 웹 UI 컨트롤에 따라 달라집니다. 일반적으로 서버 측 작업에는 의미가 없습니다.
아래에 제시된 접근 방식은 MSDN 문서와 CodeProject.com에 대한 Qureshi의 게시물을 기반으로 합니다.
참고 :이 예제는 포함 된 리소스에서 HTML 파일, 이미지 및 첨부 파일을 추출하지만 다른 대안을 사용하여 이러한 요소에 대한 스트림을 가져 오는 것은 괜찮습니다 (예 : 하드 코딩 된 문자열, 로컬 파일 등).
Stream htmlStream = null;
Stream imageStream = null;
Stream fileStream = null;
try
{
// Create the message.
var from = new MailAddress(FROM_EMAIL, FROM_NAME);
var to = new MailAddress(TO_EMAIL, TO_NAME);
var msg = new MailMessage(from, to);
msg.Subject = SUBJECT;
msg.SubjectEncoding = Encoding.UTF8;
// Get the HTML from an embedded resource.
var assembly = Assembly.GetExecutingAssembly();
htmlStream = assembly.GetManifestResourceStream(HTML_RESOURCE_PATH);
// Perform replacements on the HTML file (if you're using it as a template).
var reader = new StreamReader(htmlStream);
var body = reader
.ReadToEnd()
.Replace("%TEMPLATE_TOKEN1%", TOKEN1_VALUE)
.Replace("%TEMPLATE_TOKEN2%", TOKEN2_VALUE); // and so on...
// Create an alternate view and add it to the email.
var altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
msg.AlternateViews.Add(altView);
// Get the image from an embedded resource. The <img> tag in the HTML is:
// <img src="pid:IMAGE.PNG">
imageStream = assembly.GetManifestResourceStream(IMAGE_RESOURCE_PATH);
var linkedImage = new LinkedResource(imageStream, "image/png");
linkedImage.ContentId = "IMAGE.PNG";
altView.LinkedResources.Add(linkedImage);
// Get the attachment from an embedded resource.
fileStream = assembly.GetManifestResourceStream(FILE_RESOURCE_PATH);
var file = new Attachment(fileStream, MediaTypeNames.Application.Pdf);
file.Name = "FILE.PDF";
msg.Attachments.Add(file);
// Send the email
var client = new SmtpClient(...);
client.Credentials = new NetworkCredential(...);
client.Send(msg);
}
finally
{
if (fileStream != null) fileStream.Dispose();
if (imageStream != null) imageStream.Dispose();
if (htmlStream != null) htmlStream.Dispose();
}