C# combined with SMTP to realize mail alarm notification

Write in front

C# is an object-oriented general-purpose programming language launched by Microsoft. In addition to developing PC software, websites (with the help of  http://ASP.NET ) and APP (based on Windows Phone), it can also be used as a game script to write game logic. . SMTP is a protocol that provides reliable and effective e-mail transmission. It is a mail service based on FTP file transfer service. It is mainly used to transfer mail information between systems and provide notifications about incoming letters. Today I will mainly share with you how to implement alarm notification through C# combined with SMTP. [ Public account dotNet industrial control host computer: thinger_swj]

1 Overall thinking

C# combines SMTP to realize mail alarm notification. After analysis, we need to solve the following two problems:

  • The first question is how to detect the alarm
  • The second question is how to send mail

Below, we mainly analyze these two points in detail:

2 Alarm detection

1. In practical applications, there are two types of alarms, one is discrete alarm (i.e. digital alarm), the other is conditional alarm (i.e. data alarm), and the digital alarm is divided into rising edge detection and Falling edge detection; for conditional alarms, there are generally high-limit alarm detection, high-high alarm detection, low-limit alarm detection, and low-low alarm detection.

2. For different alarms, the detection methods will all be different, but the detection principles are the same, mainly to capture the moment when the alarm is generated, such as the rising edge of a discrete alarm. In fact, it is necessary to detect the value of this variable from False to True jumps. For the high limit of the conditional alarm, the actual value of the captured variable is greater than (or equal to) the high limit of the alarm. Therefore, the alarm detection needs to start a separate thread for real-time detection, so that the alarm information will not be missed. As for the accuracy of the alarm detection, the size of the alarm detection and the computer performance are determined.

3. Since the alarm needs to be combined with the configuration information, it cannot be displayed directly with code. The following is a combination of rising edge alarm and high limit alarm to sort out the entire process, as shown in the following figure:

3 Mail writing

For C#, it is very convenient to implement email notification. You can directly call the related class library to achieve it. Here we mainly encapsulate the class library in the form of an EmailHelper class, and then only need to call this EmailHelper. In the EmailHelper class, First, create some attributes that will be used in email sending, including sender, recipient, title, content, sender password and other information, as shown in the following figure:

···

/// <summary>
    /// 发送者
    /// </summary>
    public string mailFrom { get; set; }

    /// <summary>
    /// 收件人
    /// </summary>
    public string[] mailToArray { get; set; }

    /// <summary>
    /// 抄送
    /// </summary>
    public string[] mailCcArray { get; set; }

    /// <summary>
    /// 标题
    /// </summary>
    public string mailSubject { get; set; }

    /// <summary>
    /// 正文
    /// </summary>
    public string mailBody { get; set; }

    /// <summary>
    /// 发件人密码
    /// </summary>
    public string mailPwd { get; set; }

    /// <summary>
    /// SMTP邮件服务器
    /// </summary>
    public string host { get; set; }

    /// <summary>
    /// 正文是否是html格式
    /// </summary>
    public bool isbodyHtml { get; set; }

    /// <summary>
    /// 附件
    /// </summary>
    public string[] attachmentsPath { get; set; }

···

After completing the attribute creation, write a method to send emails. The logic of the email sending method is the same as that of normal emails. The steps are as follows:

1. Initialize the MailAddress instance with the specified mail address

2. Add email addresses to the recipient address collection

3. Add email addresses to the CC recipient address collection

4. Set sender information

5. Add attachments when there are attachments

6. Specify the sender’s email address and password to verify the sender’s identity

7. Set up SMTP mail server

8. Send mail to SMTP mail server

The specific code is as follows:

···

/// <summary>
    /// 发送邮件
    /// </summary>
    /// <returns></returns>
    public bool Send()
    {
        //使用指定的邮件地址初始化MailAddress实例
        MailAddress maddr = new MailAddress(mailFrom);
        //初始化MailMessage实例
        MailMessage myMail = new MailMessage();


        //向收件人地址集合添加邮件地址
        if (mailToArray != null)
        {
            for (int i = 0; i < mailToArray.Length; i++)
            {
                myMail.To.Add(mailToArray[i].ToString());
            }
        }

        //向抄送收件人地址集合添加邮件地址
        if (mailCcArray != null)
        {
            for (int i = 0; i < mailCcArray.Length; i++)
            {
                myMail.CC.Add(mailCcArray[i].ToString());
            }
        }
        //发件人地址
        myMail.From = maddr;

        //电子邮件的标题
        myMail.Subject = mailSubject;

        //电子邮件的主题内容使用的编码
        myMail.SubjectEncoding = Encoding.UTF8;

        //电子邮件正文
        myMail.Body = mailBody;

        //电子邮件正文的编码
        myMail.BodyEncoding = Encoding.Default;

        myMail.Priority = MailPriority.High;

        myMail.IsBodyHtml = isbodyHtml;

        //在有附件的情况下添加附件
        try
        {
            if (attachmentsPath != null && attachmentsPath.Length > 0)
            {
                Attachment attachFile = null;
                foreach (string path in attachmentsPath)
                {
                    attachFile = new Attachment(path);
                    myMail.Attachments.Add(attachFile);
                }
            }
        }
        catch (Exception err)
        {
            throw new Exception("在添加附件时有错误:" + err);
        }

        SmtpClient smtp = new SmtpClient();
        smtp.EnableSsl = true;

        //指定发件人的邮件地址和密码以验证发件人身份
        smtp.Credentials = new System.Net.NetworkCredential(mailFrom, mailPwd);


        //设置SMTP邮件服务器
        smtp.Host = host;

        try
        {
            //将邮件发送到SMTP邮件服务器
            smtp.Send(myMail);
            return true;

        }
        catch (System.Net.Mail.SmtpException ex)
        {
            return false;
        }
    }
    
    
    ···

4 Mail sending

  • Here you must first set up an email, and follow the prompts to open the following services. After activation, a password will be provided. Therefore, the password used to send the email is not the email login password, but a password generated after the following services are activated.

 

[ Public account dotNet industrial control host computer: thinger_swj]

  • In order to facilitate the establishment of the overall environment, I use Xingge Education PC Configuration Software (CMSPro) combined with Siemens S7-1200 PLC for functional testing. First, configure some variables through CMSPro, as shown in the following figure:

 

  • For each variable, configure the alarm, take the rising edge of M8.0 configuration as an example:

 

  • In the same way, set other variables to the corresponding alarm configuration. After the configuration is complete, click Save and Run:

[ Public account dotNet industrial control host computer: thinger_swj]

  • As can be seen from the above figure, the current M8.0 is False, set M8.0 manually, or set M8.0 through TIA Botu software, at this time, an alarm email will be received in the mailbox, and then M8 .0 reset, you will receive an alarm cleared email again in the mailbox, as shown in the figure below:

 

 

Guess you like

Origin blog.csdn.net/xiketangAndy/article/details/107564062