using System;
using TKMP.Writer;
using TKMP.Net;
namespace TKMP_SendMail_Gmail
{
class MailClass
{
private MailWriter mailWriter = null;
public string SmtpServer { get; set; }
public int Port { get; set; }
public string User { get; set; }
public string Pass { get; set; }
public AuthenticationProtocols Protocol { get; set; }
private string err_message = "";
public class MailClassErrorArg
{
public string Message { get; set; }
}
public delegate void MailClassError(MailClassErrorArg e);
public bool SendMail(string To, string From, string Subject, string Body, string To_J, string From_J, MailClassError mailClassError)
{
bool bResult = true;
mailWriter = new MailWriter();
try
{
mailWriter.ToAddressList.Add(To);
}
catch (Exception ex)
{
bResult = false;
}
// エラー処理
if (!bResult)
{
if (mailClassError != null)
{
MailClassErrorArg e = new MailClassErrorArg() { Message = "宛先が正しくありません" };
mailClassError(e);
}
return bResult;
}
// From が未指定や正しくない文字列の場合
try
{
mailWriter.FromAddress = From;
}
catch (Exception ex)
{
mailWriter.FromAddress = "______@gmail.com";
}
TextPart textPart = new TextPart(Body);
mailWriter.MainPart = textPart;
if (To_J != null)
{
mailWriter.Headers.Add("To", To_J + " <" + To + ">");
}
else
{
mailWriter.Headers.Add("To", To);
}
if (From_J != null)
{
mailWriter.Headers.Add("From", From_J + " <" + From + ">");
}
else
{
mailWriter.Headers.Add("From", From);
}
mailWriter.Headers.Add("Subject", Subject);
mailWriter.Headers.Add("X-Mailer", "TKMP Version 3.1.2");
var logon = new TKMP.Net.AuthLogin(User, Pass);
SmtpClient smtpClient = new SmtpClient(SmtpServer, Port, logon);
smtpClient.AuthenticationProtocol = Protocol;
try
{
if (!smtpClient.Connect())
{
err_message = "接続に失敗しました";
bResult = false;
}
else
{
smtpClient.SendMail(mailWriter);
smtpClient.Close();
}
}
catch (Exception ex)
{
err_message = ex.Message;
bResult = false;
}
// エラー処理
if (!bResult)
{
if (mailClassError != null)
{
MailClassErrorArg e = new MailClassErrorArg() { Message = err_message };
// このメソッドの引数である、ErrorHandler デリゲートを呼び出す
mailClassError(e);
}
}
return bResult;
}
// エラー処理なし
public bool SendMail(string To, string From, string Subject, string Body, string To_J, string From_J)
{
return SendMail(To, From, Subject, Body, To_J, From_J, null);
}
// 日本語なし、エラー処理なし
public bool SendMail(string To, string From, string Subject, string Body)
{
return SendMail(To, From, Subject, Body, null, null, null);
}
}
}