SendGrid 應用

 SendGrid 是用於寄信使用的,需要去註冊帳號以及申請API KEY之類的。

可以使用免費的KEY


using SendGrid;

using SendGrid.Helpers.Mail;


public async Task<Response> SendGridMailAttachment(string APIKey, string Subject, string MailFrom, string MailSendPerson, string ToMails, string Content, string FileName, byte[]? byteData, string Mailcc = "" , string Mailbcc = "")

{

    string fromName = string.Empty, htmlContent = string.Empty;


    SendGridClient? sendGrid = null;

    EmailAddress? from = null;

    List<EmailAddress>? to = new List<EmailAddress>();

    List<EmailAddress>? cc = new List<EmailAddress>();

    List<EmailAddress>? bcc = new List<EmailAddress>();


    SendGridMessage? msg = null;


    Attachment? attachment = null;


    Response? response = null;


    try

    {

        sendGrid = new SendGridClient(APIKey);


        #region 寄件人 , 寄件人呈現

        from = new EmailAddress(MailFrom, MailSendPerson);

        #endregion


        #region 收件人

        string[] toMailArr = ToMails.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);


        for (int i = 0; i < toMailArr.Length; i++)

        {

            string mail = toMailArr[i];


            if (IsMail(mail) == true)

            {

                to.Add(new EmailAddress(toMailArr[i]));

            }

            else

            {

                _logger.LogError($"Mail格式錯誤:{mail}");

            }

        }

        #endregion


        if (to.Count == 0)

        {

            throw new Exception("沒有Mail,請確認格式");

        }


        htmlContent = string.Format("{0}", Content);


        //無法使用官方共用函式 無法滿足條件

        //msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, Subject, Content, htmlContent);

        //一封信內含多個收件者

        msg = new SendGridMessage()

        {

            From = from,

            Subject = Subject,

            HtmlContent = htmlContent,

        };


        msg.AddTos(to);


        #region CC

        //是否有cc

        if (!string.IsNullOrEmpty(Mailcc))

        {

            foreach (var list in Mailcc.Split(';'))

            {

                if (IsMail(list))

                    cc.Add(new EmailAddress(list));

                else

                    _logger.LogError($"Mail格式錯誤:{list}");

            }


            msg.AddCcs(cc);

        }

        #endregion


        #region BCC

        //是否有cc

        if (!string.IsNullOrEmpty(Mailbcc))

        {

            foreach (var list in Mailbcc.Split(';'))

            {

                if (IsMail(list))

                    bcc.Add(new EmailAddress(list));

                else

                    _logger.LogError($"Mail格式錯誤:{list}");

            }


            msg.AddBccs(bcc);

        }

        #endregion


        #region 附件

        if (byteData != null && byteData.Length > 0)

        {

            attachment = new Attachment();

            attachment.Content = Convert.ToBase64String(byteData);

            attachment.Type = "application/zip";

            attachment.Filename = FileName;


            msg.AddAttachment(attachment);

        }

        #endregion


        response = await sendGrid.SendEmailAsync(msg).ConfigureAwait(false);


        _logger.LogDebug($"SendGridMailAttachment.response{JsonConvert.SerializeObject(response)}");


        return response;

    }

    catch (Exception ex)

    {

        _logger.LogError(ex.ToString());

        if (response.StatusCode == null)

            response.StatusCode = System.Net.HttpStatusCode.NotFound;


        return response;

    }

    finally

    {

        if (response != null)

        {

            response = null;

        }


        if (attachment != null)

        {

            attachment = null;

        }


        if (byteData != null)

        {

            byteData = null;

        }


        if (msg != null)

        {

            msg = null;

        }


        if (to != null && to.Count > 0)

        {

            to.Clear();

        }


        if (from != null)

        {

            from = null;

        }


        if (sendGrid != null)

        {

            sendGrid = null;

        }


    }

}


public bool IsMail(string MailData)

{

    bool bResult;

    try

    {

        System.Net.Mail.MailAddress mail = new System.Net.Mail.MailAddress(MailData);


        bResult = true;

    }

    catch

    {

        bResult = false;

    }


    return bResult;

}


參考:https://codepulse.com.tw/zh-tw/gcp-%E9%9B%BB%E5%95%86%E7%B6%B2%E7%AB%99%E6%9E%B6%E8%A8%AD%E6%95%99%E5%AD%B8-%E6%95%99%E4%BD%A0%E5%A6%82%E4%BD%95%E7%94%A8-sendgrid-%E7%82%BA%E4%BD%A0%E7%9A%84%E7%B6%B2%E7%AB%99%E7%99%BC%E4%BF%A1

留言

這個網誌中的熱門文章

無法載入檔案或組件 'System.IO.Compression' 或其相依性的其中之一。

MongoDB 入門

javascript 更改屬性及創建標籤