Если вы не установили пакет Nuget в SendGrid, установите его.
Далее, без какого-либо конкретного вопроса об их API, я не уверен, что сказать.Я выложу часть своего кода.
Их API немного сложен в использовании по сравнению с тем, что есть в System.Net.Mail.Поэтому я написал некоторый код, который преобразует System.Net.Mail.MailMessage в SendGridMessage.Затем я создаю объекты MailMessage и использую код конверсии для отправки электронного письма.
Это в основном то, что я бы вставил в ваш код.
public ActionResult AddToCohort([Bind(Include = "ID,CohortId,RegistrationId,Notes,CoachId,ContractStatus,DepositStatus,PortalMemberId,ProfileImageURL,ProfileComment,PersonalityScoreD,PersonalityScoreI,PersonalityScoreS,PersonalityScoreC,EnglishProefficiencyBefore,EnglishProefficiencyAfter,SlackHandle,GraduationStatus,GitHubHandle")] CohortSubscriptions cohortSubscriptions)
{
if (ModelState.IsValid)
{
var newcohortAssignments = cohortSubscriptions;
newcohortAssignments.ContractStatus = "Pending";
newcohortAssignments.DepositStatus = "Pending";
newcohortAssignments.GraduationStatus = "Not Graduated";
db.CohortSubscriptions.Add(cohortSubscriptions);
db.SaveChanges();
using (var message = new MailMessage())
{
message.From = new MailAddress("me@here.com");
message.To.Add("someone@somewhere.com");
message.Body += "Hello world!";
message.IsBodyHtml = true;
MailHelper.SendMail(message);
}
return RedirectToAction("CohortAssignments", "Home");
}
ViewBag.CohortId = new SelectList(db.Cohorts, "ID", "Name", cohortSubscriptions.CohortId);
return View(cohortSubscriptions);
}
Ниже приводится мой код конверсии.Он ищет ваш ключ API в Web.Config в наборе приложений с именем ApiKey.О, также он использует JetBrains.Annotations.Поэтому установите этот пакет Nuget или удалите мои аннотации из кода.
MailHelper.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using JetBrains.Annotations;
using SendGrid;
using SendGrid.Helpers.Mail;
using Attachment = SendGrid.Helpers.Mail.Attachment;
[assembly: CLSCompliant(true)]
namespace Bc3.Mail
{
/// <summary>
/// Helper to send messages created with
/// System.Net.Mail.Message through SendGrid
/// </summary>
[PublicAPI]
public static class MailHelper
{
/// <summary>
/// The helper function that send the MailMessage through SendGrid.
/// It's successful when HttpStatusCode.OK or HttpStatusCode.Accepted
/// is returned
/// </summary>
/// <param name="mail"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
[NotNull]
public static Tuple<HttpStatusCode, string> SendMail([NotNull]MailMessage mail)
{
if (mail is null)
throw new ArgumentNullException(nameof(mail));
var from = mail.From;
if (from is null)
return new Tuple<HttpStatusCode, string>(HttpStatusCode.BadRequest,
"No from address");
if (mail.To.Count == 0)
return new Tuple<HttpStatusCode, string>(HttpStatusCode.BadRequest,
"No to address");
var to = mail.To[0];
if (to is null)
return new Tuple<HttpStatusCode, string>(HttpStatusCode.BadRequest,
"No to address");
SendGridMessage message;
if (mail.To.Count == 1)
{
message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail(ConvertAddress(from),
ConvertAddress(to),
mail.Subject,
string.Empty,
mail.Body);
}
else
{
var tos = from address in mail.To
where address is null == false
select ConvertAddress(address);
message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmailToMultipleRecipients(
ConvertAddress(from),
tos.ToList(),
mail.Subject,
string.Empty,
mail.Body);
}
var personalization = message?.Personalizations?[0];
if (personalization is null)
return new Tuple<HttpStatusCode, string>(HttpStatusCode.InternalServerError, "Error creating email message");
if (mail.CC.Count != 0)
{
personalization.Ccs = new List<EmailAddress>();
foreach (var cc in mail.CC)
personalization.Ccs.Add(ConvertAddress(cc));
}
if (mail.Bcc.Count != 0)
{
personalization.Bccs = new List<EmailAddress>();
foreach (var bcc in mail.Bcc)
personalization.Bccs.Add(ConvertAddress(bcc));
}
if (mail.Attachments.Count != 0)
{
if (message.Attachments is null)
message.Attachments = new List<Attachment>();
foreach (var attachment in mail.Attachments)
{
if (attachment.ContentStream is null)
continue;
var sendGridAttachment = new Attachment();
using (var sr = new StreamReader(attachment.ContentStream))
sendGridAttachment.Content = Convert.ToBase64String(
Encoding.UTF8.GetBytes(
sr.ReadToEnd()));
sendGridAttachment.Filename = attachment.Name;
sendGridAttachment.Type = attachment.ContentType.MediaType;
message.Attachments.Add(sendGridAttachment);
}
}
if (message.Headers is null)
message.Headers = new Dictionary<string, string>();
foreach (var key in mail.Headers.AllKeys)
{
var header = mail.Headers[key];
if (header is null)
continue;
if (message.Headers.ContainsKey(header) == false)
message.Headers.Add(key, header);
}
var (httpStatusCode, errorMessage) = SendMessage(message);
return new Tuple<HttpStatusCode, string>(httpStatusCode, errorMessage);
}
[NotNull]
private static Tuple<HttpStatusCode, string> SendMessage([NotNull]SendGridMessage message)
{
try
{
var apiKey = ConfigurationManager.AppSettings["ApiKey"];
var client = new SendGridClient(apiKey);
var sendTask = client.SendEmailAsync(message);
if (sendTask is null)
return new Tuple<HttpStatusCode, string>(HttpStatusCode.BadRequest, "Email status not received");
sendTask.Wait();
var response = sendTask.Result;
if (response is null)
return new Tuple<HttpStatusCode, string>(HttpStatusCode.BadRequest, "Email status not received");
if (response.StatusCode == HttpStatusCode.OK
|| response.StatusCode == HttpStatusCode.Accepted)
return new Tuple<HttpStatusCode, string>(response.StatusCode, null);
if (response.Body is null)
return new Tuple<HttpStatusCode, string>(response.StatusCode, null);
var task = response.Body.ReadAsStringAsync();
task.Wait();
return new Tuple<HttpStatusCode, string>(response.StatusCode, task.Result);
}
catch (Exception exception)
{
return new Tuple<HttpStatusCode, string>(HttpStatusCode.InternalServerError, exception.Message);
}
}
[NotNull]
private static EmailAddress ConvertAddress([NotNull]MailAddress address)
{
return new EmailAddress(address.Address, address.DisplayName);
}
}
}