发送带有 SendGrid 和空值的邮件?

Send mail with SendGrid and null values?

我在 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");

但如果不想发送抄送则不是这个

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

或这个

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

尝试设置默认值并检查 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");