使用 SendGrid 和空值发送邮件

本文关键字:空值 SendGrid 使用 | 更新日期: 2023-09-27 18:33:04

我在 asp.net C#中使用SendGrid。我有这个功能来发送邮件

public async Task SendMail(string AddTo, string Addcc, string Subject, string Message)
{
    var myMessage = new SendGrid.SendGridMessage();
    myMessage.AddTo(AddTo);
    myMessage.AddCc(Addcc);
    myMessage.From = new MailAddress("noreply@noreply.se");
    myMessage.Subject = Subject;
    myMessage.Html = Message;
    var credentials = new NetworkCredential(
       ConfigurationManager.AppSettings["mailAccount"],
       ConfigurationManager.AppSettings["mailPassword"]
       );
    //Some validation code
}

我需要将AddCc添加到一些邮件中,但不是全部。这工作正常。

SendMail("mailadress1@gmail.com", "mailadress2@gmail.com", "Subject", "Message");

但如果不想发送 CC,则不是这个

SendMail("mailadress1@gmail.com", "null", "Subject", "Message");

或者这个

SendMail("mailadress1@gmail.com", "", "Subject", "Message");

使用 SendGrid 和空值发送邮件

尝试设置

默认值并检查AddCc是否null

public async Task SendMail(string AddTo, string Addcc = null, string Subject, string Message)
{
    var myMessage = new SendGrid.SendGridMessage();
    myMessage.AddTo(AddTo);
    if(AddCc != null)
    {
        myMessage.AddCc(Addcc);
    }
    myMessage.From = new MailAddress("noreply@noreply.se");
    myMessage.Subject = Subject;
    myMessage.Html = Message;
    var credentials = new NetworkCredential(
       ConfigurationManager.AppSettings["mailAccount"],
       ConfigurationManager.AppSettings["mailPassword"]
       );
    //Some validation code
}

有了这个,您可以这样称呼它:

SendMail("mailadress1@gmail.com", "mailadress2@gmail.com", "Subject", "Message");

并且没有抄送:

SendMail("mailadress1@gmail.com", "Subject", "Message");

您甚至可以执行以下操作:

SendMail("mailadress1@gmail.com", null, "Subject", "Message");