c# - 在 SendGrid C# 中将电子邮件作为日历邀请/约会发送

标签 c# email azure outlook sendgrid

我想向 Outlook 以及非 Outlook 客户端(例如 gmail/yahoo)发送一封包含日历邀请/约会的电子邮件。我的应用程序托管在 Azure 上,我使用 SendGrid 发送电子邮件。电子邮件部分工作得很好,但我还没有找到任何可以与 Outlook 和其他电子邮件客户端一起使用的完整工作解决方案。这是我用来发送电子邮件的代码片段:

var client = new SendGridClient(this.apiKey);
var msg = MailHelper.CreateSingleEmailToMultipleRecipients(
            new EmailAddress(Sender, SenderName),
            recipients, subject, textcontent, htmlcontent);

if (isMeetingRequest)
{
    Attachment attachment = new Attachment(); 
    attachment.Filename = "calendar.ics";
    attachment.Content = htmlcontent;
    attachment.Type = "text/calendar";
    msg.Attachments = new List<Attachment> { attachment };
}
await client.SendEmailAsync(msg);

htmlContent 来自形成日历邀请字符串的另一个编码片段:

private static string MeetingRequestString(string from, List<string> toUsers, string subject, string desc, DateTime startTime, DateTime endTime)
    {
        StringBuilder str = new StringBuilder();

        str.AppendLine("BEGIN:VCALENDAR");
        str.AppendLine("PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN");
        str.AppendLine("VERSION:2.0");
        str.AppendLine(string.Format("METHOD:REQUEST"));
        str.AppendLine("BEGIN:VEVENT");

        str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", startTime));
        str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.Now));
        str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", endTime));
        str.AppendLine(string.Format("UID:{0}", Guid.NewGuid().ToString()));
        str.AppendLine(string.Format("DESCRIPTION:{0}", desc.Replace("\n", "<br>")));
        str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", desc.Replace("\n", "<br>")));
        str.AppendLine(string.Format("SUMMARY:{0}", subject));

        str.AppendLine(string.Format("ORGANIZER;CN=\"{0}\":MAILTO:{1}", from, from));
        str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", string.Join(",", toUsers), string.Join(",", toUsers)));

        str.AppendLine("BEGIN:VALARM");
        str.AppendLine("TRIGGER:-PT15M");
        str.AppendLine("ACTION:DISPLAY");
        str.AppendLine("DESCRIPTION:Reminder");
        str.AppendLine("END:VALARM");
        str.AppendLine("END:VEVENT");
        str.AppendLine("END:VCALENDAR");

        return str.ToString();
    }

这似乎不起作用。有什么指点吗?

最佳答案

根据您的描述,我检查了此问题并尝试发送带有日历附件的电子邮件。您可以引用以下代码片段:

static async Task SendGridAsync()
{
    var client = new SendGridClient("your-api-key");

    var msg = new SendGridMessage()
    {
        From = new EmailAddress("{sender-email}", "{sender-name}"),
        Subject = "Hello World from the SendGrid CSharp SDK!",
        HtmlContent = "<strong>Hello, Email using HTML!</strong>"
    };
    var recipients = new List<EmailAddress>
    {
        new EmailAddress("{recipient-email}", "{recipient-name}")
    };
    msg.AddTos(recipients);

    string CalendarContent = MeetingRequestString("{ORGANIZER}", new List<string>() { "{ATTENDEE}" },"{subject}","{description}", "{location}", DateTime.Now, DateTime.Now.AddDays(2));
    byte[] calendarBytes = Encoding.UTF8.GetBytes(CalendarContent.ToString());
    SendGrid.Helpers.Mail.Attachment calendarAttachment = new SendGrid.Helpers.Mail.Attachment();
    calendarAttachment.Filename = "invite.ics";
    //the Base64 encoded content of the attachment.
    calendarAttachment.Content = Convert.ToBase64String(calendarBytes);
    calendarAttachment.Type = "text/calendar";
    msg.Attachments = new List<SendGrid.Helpers.Mail.Attachment>() { calendarAttachment };

    var response = await client.SendEmailAsync(msg);
}


private static string MeetingRequestString(string from, List<string> toUsers, string subject, string desc, string location, DateTime startTime, DateTime endTime, int? eventID = null, bool isCancel = false)
{
    StringBuilder str = new StringBuilder();

    str.AppendLine("BEGIN:VCALENDAR");
    str.AppendLine("PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN");
    str.AppendLine("VERSION:2.0");
    str.AppendLine(string.Format("METHOD:{0}", (isCancel ? "CANCEL" : "REQUEST")));
    str.AppendLine("BEGIN:VEVENT");

    str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", startTime.ToUniversalTime()));
    str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.Now));
    str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", endTime.ToUniversalTime()));
    str.AppendLine(string.Format("LOCATION: {0}", location));
    str.AppendLine(string.Format("UID:{0}", (eventID.HasValue ? "blablabla" + eventID : Guid.NewGuid().ToString())));
    str.AppendLine(string.Format("DESCRIPTION:{0}", desc.Replace("\n", "<br>")));
    str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", desc.Replace("\n", "<br>")));
    str.AppendLine(string.Format("SUMMARY:{0}", subject));

    str.AppendLine(string.Format("ORGANIZER;CN=\"{0}\":MAILTO:{1}", from, from));
    str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", string.Join(",", toUsers), string.Join(",", toUsers)));

    str.AppendLine("BEGIN:VALARM");
    str.AppendLine("TRIGGER:-PT15M");
    str.AppendLine("ACTION:DISPLAY");
    str.AppendLine("DESCRIPTION:Reminder");
    str.AppendLine("END:VALARM");
    str.AppendLine("END:VEVENT");
    str.AppendLine("END:VCALENDAR");

    return str.ToString();
}

结果:

enter image description here

enter image description here

关于c# - 在 SendGrid C# 中将电子邮件作为日历邀请/约会发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45076896/

相关文章:

asp.net-mvc - ASP MVC - 前端和后端

azure - 使用 Azure 保持数据库对象同步

C# 和 MongoDriver - 如何从外部集合中获取值(聚合 + 查找)?

php - 无法连接到 SMTP 服务器。在 CakePHP 中

azure - Azure 目录中应用程序的回调 URL

PHP 从多维数组 (IMAP) 创建消息线程的多维数组

javascript - 在 Lambda 函数中从 AWS SES 发送电子邮件时访问被拒绝

c# - 如何在多线程环境中保持对象成员变量对线程私有(private)

c# - 使用接口(interface)的隐式运算符

c# - 如何更改菜单悬停颜色