반응형
public class EmailHelper : IDisposable
{

	private readonly MailAddress sendAddress;
	private readonly SmtpClient smtp;
	private bool disposed;
	private bool isAsynSuccess = false;
	private Stopwatch stopWatch;
	private System.Timers.Timer sysTimer;

	public event SendCompletedEventHandler SendCompleted;

	public EmailHelper(string host, int port, bool enableSsl, string fromEmail, string password)
	{
		this.sendAddress = new MailAddress(fromEmail);

		smtp = new SmtpClient
		{
			Host = host,
			Port = port,
			EnableSsl = enableSsl,
			DeliveryMethod = SmtpDeliveryMethod.Network,
			UseDefaultCredentials = false,
			Credentials = new NetworkCredential(sendAddress.Address, password),
			Timeout = 200000
		};
	}

	~EmailHelper()
	{
		this.Dispose(false);
	}

	public void Dispose()
	{
		this.Dispose(true);
		GC.SuppressFinalize(this);
	}

	public bool SendEmail(
		string targetAddress,
		string subject,
		string body,
		List<string> attachmentFiles = null)
	{
		bool isSuccess = false;
		MailMessage message = null;

		try
		{
			if (string.IsNullOrEmpty(targetAddress))
			{
				throw new Exception("target email address is empty");
			}

			MailAddress toAddress = new MailAddress(targetAddress);

			message = new MailMessage(sendAddress, toAddress)
			{
				Subject = subject,
				Body = body,
			};

			if (attachmentFiles != null)
			{
				foreach (var filePath in attachmentFiles)
				{
					if (!File.Exists(filePath)) continue;
					message.Attachments.Add(new Attachment(filePath));
				}
			}

			smtp.Send(message);

			isSuccess = true;
		}
		catch (Exception ex)
		{
			throw ex;
		}
		finally
		{
			if (message != null) message.Dispose();
		}

		return isSuccess;
	}

	public bool SendEmailAsync(string targetAddress, string subject, string body, List<string> attachmentFiles = null)
	{
		MailMessage message = null;
		smtp.SendCompleted += Smtp_SendCompleted;

		sysTimer = new System.Timers.Timer(smtp.Timeout);
		sysTimer.Elapsed += SysTimer_Elapsed;
		sysTimer.Start();

		try
		{
			if (string.IsNullOrEmpty(targetAddress))
			{
				throw new Exception("target email address is empty");
			}

			MailAddress toAddress = new MailAddress(targetAddress);
			message = new MailMessage(sendAddress, toAddress)
			{
				Subject = subject,
				Body = body,
			};

			if (attachmentFiles != null)
			{
				foreach (var filePath in attachmentFiles)
				{
					if (!File.Exists(filePath)) continue;
					message.Attachments.Add(new Attachment(filePath));
				}
			}

			stopWatch = new Stopwatch();
			stopWatch.Start();
			isAsynSuccess = false;

			Task sendTask = smtp.SendMailAsync(message);
			sendTask.Wait();
		}
		catch (AggregateException aggEx)
		{
			var innerException = aggEx.InnerException as TaskCanceledException;
			if (innerException == null)
			{
				throw aggEx;
			}
		}
		catch (Exception ex)
		{
			throw ex;
		}
		finally
		{
			sysTimer.Stop();
			sysTimer.Elapsed -= SysTimer_Elapsed;
			sysTimer.Dispose();
			sysTimer = null;
			stopWatch = null;

			smtp.SendCompleted -= Smtp_SendCompleted;
			if (message != null)
			{
				message.Dispose();
			}
		}

		return isAsynSuccess;
	}

	protected virtual void Dispose(bool disposing)
	{
		if (this.disposed) return;
		if (disposing)
		{
			if (smtp != null) smtp.Dispose();
		}

		this.disposed = true;
	}

	protected void OnSendCompleted(AsyncCompletedEventArgs e)
	{
		this.SendCompleted?.Invoke(this, e);
	}

	private void Smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
	{
		if (e.Error != null)
		{
			isAsynSuccess = false;
			return;
		}
		else if (e.Cancelled)
		{
			isAsynSuccess = false;
			return;
		}
		else
		{
			isAsynSuccess = true;
		}
	}

	private void SysTimer_Elapsed(object sender, ElapsedEventArgs e)
	{
		smtp.SendAsyncCancel();
	}

}
반응형

+ Recent posts