开发用于发送电子邮件的 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属性中。此属性包含一个在响应后将自动添加为收件人的地址列表。为了处理可能的异常,在 try/catch 结构中封装了SmtpClient的Send方法。
- 更改var fromAddress变量值以反映发件人电子邮件。
- 更改var toAddress变量值以反映收件人电子邮件。小贴士: 在本示例中,电子邮件将发送给单个收件人,但是,您可以使用MailMessage类的To属性添加更多收件人。请参见 MailMessage.To 属性 (System.Net.Mail) | Microsoft 文档例如:mailMessage.To.Add(new MailAddress(...)
- 如果需要,通过修改const string fromPassword = "Insert your password here.";提供电子邮件帐户的密码重要提示: 如果使用双重身份验证来保护电子邮件帐户,则必须为应用程序生成密码。
- 如果需要,在var smtpClient变量值中配置Credentials数据。
- 保存代码。
提供反馈