如何使用C#代码发送邮件通知

时间:2018-08-07 05:50:26

标签: c#-4.0

我已使用以下代码使用C#代码发送邮件通知

public static void SendNotification(string filepath)
        {
            try
            {
                SmtpClient mailServer = new SmtpClient(ConfigurationManager.AppSettings["host"], int.Parse(ConfigurationManager.AppSettings["portnumber"]));
                mailServer.EnableSsl = true;
                mailServer.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["sender_username"], ConfigurationManager.AppSettings["sender_password"]);
                string from = ConfigurationManager.AppSettings["sender"];
                string to = ConfigurationManager.AppSettings["receipients"];
                string cc = ConfigurationManager.AppSettings["receipientCC"];
                MailMessage msg = new MailMessage(from, to);
                msg.Subject = "Branch API Export Results";
                msg.Body = "Test Mail. Please Find Attached for the Results from Branch API Export";
                msg.CC.Add(cc);
                msg.Attachments.Add(new Attachment(filepath));
                mailServer.Send(msg);
            }
            catch (Exception ex)
            {
                //Log
            }
        }

在App.Config中包含配置值。除此之外,还有其他更好的方法。

1 个答案:

答案 0 :(得分:1)

在这里。

 private static void SendMail(string subject, string content)
{
    try

    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
        mail.From = new MailAddress("YOURMAİL");
        mail.To.Add("MAİLTO");
        mail.Subject = subject;
        mail.Body = content;
        SmtpServer.Port = 25;
        SmtpServer.Credentials = new System.Net.NetworkCredential("YOURMAİL", "YOURMAİLPASSWORD");
        SmtpServer.EnableSsl = true;
        SmtpServer.Send(mail);
    }
    catch (Exception ex)
    {

    }
}

这是发送邮件的最简单方法。不要忘记使用System.Net.Mail进行添加;