あけましておめでとうございます。
毎年、適当な言語を選んで、あけましておめでとうメールを送っています。
今年は c# にしてみました。
Environment
- 開発環境: Windows 10 pro
- 開発ツール: Visual Studio 2019 + dotent core sdk 3.1
- 実行環境: Ubuntu 18.04.1 LTS x64
Code
SmtpClientクラスはもう廃止なんですね。
https://docs.microsoft.com/ja-jp/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8
重要
新しい開発には SmtpClient クラスを使用しないことをお勧めします。 SmtpClient は多くの最新プロトコルをサポートしていないためです。 代わりにMailkitまたはその他のライブラリを使用してください。 詳細については、GitHub でSmtpclient を使用しないことをお勧めします。
MSの公式ドキュメントにはMailkitを使えと。オープンな社風になってしまったMSに私は戸惑いを隠しきれません。
というので nuget で Mailkitをインストールしてgithubのサンプルコードを使いました。
usingSystem;usingMailKit.Net.Smtp;usingMailKit;usingMimeKit;usingSystem.Collections.Generic;namespacemail{publicclassProgram{publicstaticvoidMain(string[]args){varmsg=newCustomMessage(){Subject="I wish you a Happy new year 2020",From="dharry@example.co.jp",SmtpServer="mail.example.co.jp",AuthUser="dharry",AuthPass="mypass",};msg.To=newList<KeyValuePair<string,string>>(){newKeyValuePair<string,string>("山田","yamada@example.com"),newKeyValuePair<string,string>("斎藤","saito@example.com")newKeyValuePair<string,string>("佐藤","sato@example.com")};msg.Body=body;msg.Send();}privateconststringbody=@"2020年01月01日になりました。
あけましておめでとうございます。
今年もよろしくお願いします。
";}publicclassCustomMessage{publicList<KeyValuePair<string,string>>To{get;set;}publicstringSubject{get;set;}publicstringFrom{get;set;}publicstringBody{get;set;}publicstringSmtpServer{get;set;}publicintSmtpPort{get;set;}=587;publicstringAuthUser{get;set;}publicstringAuthPass{get;set;}publicvoidSend(){foreach(varpinTo){varmessage=newMimeMessage();message.From.Add(newMailboxAddress(From));message.To.Add(newMailboxAddress(p.Key,p.Value));message.Subject=Subject;message.Body=newTextPart("plain"){Text=$"{p.Key}さん\n\n{Body}"};using(varclient=newSmtpClient()){// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)client.ServerCertificateValidationCallback=(s,c,h,e)=>true;client.Connect(SmtpServer,SmtpPort,false);// Note: only needed if the SMTP server requires authenticationclient.Authenticate(AuthUser,AuthPass);client.Send(message);client.Disconnect(true);Console.WriteLine($"sendmessage.. {p.Value}");}}}}}Execute
ビルド->発行して、Linuxに持っていき、実行。
毎回思うのだが、dotnetコマンドの引数にdllというのが違和感ありすぎて困ります。
$ dotnet ./mail.dll