メール送信用 NetLogic を開発する
この NetLogic は、事前定義済みアドレスに電子メールを送信します。
- NetLogic の作成:
- [プロジェクトビュー]で、[NetLogic]フォルダーを右クリックし、 を選択します。
- NetLogic にカーソルを合わせ、を選択し、EmailSenderと入力します。
- NetLogic をダブルクリックします。外部コード エディターが開きます。
- コードエディターで、次の操作を行います。
- 既存のコードを次のコードに置き換えます:using System; using System.Net.Mail; using System.Net; using UAManagedCore; using FTOptix.NetLogic; public class EmailSender : BaseNetLogic { [ExportMethod] public void SendEmail(string replyToAddress, string mailSubject, string mailBody) { if (string.IsNullOrEmpty(replyToAddress) || mailSubject == null || mailBody == null) { Log.Error("EmailSender", "Invalid values for one or more parameters."); return; } var fromAddress = new MailAddress("mail@domain.com", "Name"); // Email Sender var toAddress = new MailAddress("mail@domain.com", "Name"); // Email Receiver // Password for SMTP server authentication if necessary const string fromPassword = "Insert your password here."; var smtpClient = new SmtpClient { // Fill the following lines with your SMTP server info Host = "smtp.domain.com", Port = 587, EnableSsl = true, // Set to true if the server requires SSL. DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; var message = new MailMessage() { // Create the message. Subject = mailSubject, Body = mailBody }; // Specify the sender message.From = fromAddress; // Recipient emails // The MailMessage.To property is a collection of emails, so you can add different recipients using: // message.To.Add(new MailAddress(...)); message.To.Add(toAddress); // Add reply-to address message.ReplyToList.Add(replyToAddress); try { // Send email message smtpClient.Send(message); Log.Info("Message " + mailSubject + " sent successfully."); } catch (Exception ex) { // Insert here actions to be performed in case of an error when sending an email Log.Error("Error while sending message " + mailSubject + ", please try again. " + ex.Message); } } }ヒント: この例では、ランタイムに入力された電子メールがReplyToListプロパティに追加されます。このプロパティには、応答のイベントで受信者として自動的に追加されるアドレスのリストが含まれています。SmtpClientのSendメソッドは、起こりうる例外を処理するために try/catch コンストラクト内にカプセル化されます。
- 送信者の電子メールを反映するようにvar fromAddress変数値を変更します。
- var toAddress変数値を変更して、受信者の電子メールを反映させます。ヒント: この例では、メールは 1 人の受信者に送信されますが、MailMessageクラスのToプロパティを使用すれば、さらに受信者を追加することができます。「MailMessage.To Property (System.Net.Mail) | Microsoft Docs」を参照例:mailMessage.To.Add(new MailAddress(...)
- 必要に応じて、const string fromPassword = "Insert your password here.";を変更して電子メール アカウントにパスワードを入力します重要: 2 要素認証を使用してメールアカウントを保護する場合は、アプリケーションのパスワードを生成する必要があります。
- 必要に応じて、var smtpClient変数値でCredentialsデータを構成します。
- コードを保存します。
ご質問やご意見