[C#/COMMON] SmtpClient 클래스 : DeliveryMethod/PickupDirectoryLocation 속성을 사용해 EML 파일 저장하기 (기능 개선)

■ SmtpClient 클래스의 DeliveryMethod/PickupDirectoryLocation 속성을 사용해 EML 파일을 저장하는 방법을 보여준다. (기능 개선)

test.eml (생성 파일)

using System;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Reflection;

namespace TestProject
{
/// <summary>
/// 메일 메시지 확장
/// </summary>
public static class MailMessageExtension
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Static
//////////////////////////////////////////////////////////////////////////////// Public

#region 저장하기 – Save(mailMessage, stream)

/// <summary>
/// 저장하기
/// </summary>
/// <param name="mailMessage">메일 메시지</param>
/// <param name="stream">스트림</param>
public static void Save(this MailMessage mailMessage, Stream stream)
{
using(SmtpClient smtpClient = new SmtpClient())
{
string temporaryDirectoryPath = Path.Combine
(
Path.GetTempPath(),
Assembly.GetExecutingAssembly().GetName().Name,
"temp",
Guid.NewGuid().ToString()
);

if(!Directory.Exists(temporaryDirectoryPath))
{
Directory.CreateDirectory(temporaryDirectoryPath);
}

smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
smtpClient.PickupDirectoryLocation = temporaryDirectoryPath;

smtpClient.Send(mailMessage);

string filePath = Directory.GetFiles(temporaryDirectoryPath).Single();

using(FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
fileStream.CopyTo(stream);
}

if(Directory.Exists(temporaryDirectoryPath))
{
Directory.Delete(temporaryDirectoryPath, true);
}
}
}

#endregion
#region 저장하기 – Save(mailMessage, filePath)

/// <summary>
/// 저장하기
/// </summary>
/// <param name="mailMessage">메일 메시지</param>
/// <param name="filePath">파일 경로</param>
public static void Save(this MailMessage mailMessage, string filePath)
{
using(FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
mailMessage.Save(fileStream);
}
}

#endregion
}
}
—————————————————————————————————-

Program.cs

TestProject.zip
test.zip

Advertisements