【C#】MailKitを使用した際にハマった点
今回はMailKitを使用した際にハマった点をこの記事で説明します。
この記事のポイント・PORTの設定
MailKitの使用
前回説明した通り、通常MailKitを使用するには以下のように設定します。
using MailKit.Net.Smtp;
using MimeKit;
using System;
using static System.Console;
namespace Sample.Models
{
public class Mail
{
public static bool sendMail(string toAddress, string password, ref string errmsg)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(Constants.EMAIL_FROM_NAME, Constants.EMAIL_FROM_ADDRESS)); // 送信元MailAddress
message.To.Add(new MailboxAddress(Constants.EMAIL_TO_NAME, toAddress)); // 送信先MailAddress
message.Subject = Constants.EMAIL_SUBJECT; // Mail Title
message.Body = new TextPart("plain")
{
Text = Constants.EMAIL_TEXT.Replace("{1}", password).Replace("{2}", Constants.PERIO_PERIO_URL) // Mail本文
};
using (var client = new SmtpClient())
{
try
{
// Set SMTP(Server,Port)
client.Connect(Constants.EMAIL_SMTP_SERVER, Constants.EMAIL_PORT_NO, MailKit.Security.SecureSocketOptions.Auto);
WriteLine("接続完了");
// Set UserId,Password
client.Authenticate(Constants.EMAIL_USER_ID, Constants.EMAIL_PASSWORD);
WriteLine("認証完了");
client.Send(message);
WriteLine("送信完了");
client.Disconnect(true);
WriteLine("切断");
return true;
}
catch (Exception ex)
{
WriteLine(ex.ToString());
errmsg = ex.ToString();
return false;
}
}
}
}
}
PORT_NOに587を設定
// Set SMTP(Server,Port)
client.Connect(Constants.EMAIL_SMTP_SERVER,
Constants.EMAIL_PORT_NO,
↑ここのPORT_NOはSTARTTLSの場合、一般的に587を設定
MailKit.Security.SecureSocketOptions.Auto);
ローカル環境では問題なくメールが送信できるのにいざ、サーバにデプロイするとエラーに…
サーバはAWSのAmazonLightSail(WindowsServer2016、IISを構築)を使用しているのでFWかIISの設定だと思い、設定するも送信できず…
PORT_NOを465に変更
// Set SMTP(Server,Port)
client.Connect(Constants.EMAIL_SMTP_SERVER,
Constants.EMAIL_PORT_NO,
↑ここのPORT_NOはSMTPSの場合、一般的に465を設定
MailKit.Security.SecureSocketOptions.Auto);
PORT_NOを465に変更し、サーバにデプロイすると…な、なんと問題なくメールが送れました。
結局原因は…
単純にPORT_NOの問題なのか不明です。(FWとかPORTとかSMTPとか専門分野でないのでサッパリです…これを機に勉強しようっと)
根本的な解決になっておりませんが、もし同様な問題が発生している方がいらっしゃましたら、PORT_NOを変更して試してみてはいかがでしょうか。
< |