本文整理汇总了C#中SendGrid.SendGridMessage.AddAttachment方法的典型用法代码示例。如果您正苦于以下问题:C# SendGridMessage.AddAttachment方法的具体用法?C# SendGridMessage.AddAttachment怎么用?C# SendGridMessage.AddAttachment使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SendGrid.SendGridMessage
的用法示例。
在下文中一共展示了SendGridMessage.AddAttachment方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EmailReceipt
public void EmailReceipt(byte[] file, string fileName, OrderViewModel order)
{
// Set our SendGrid API User and Key values for authenticating our transport.
var sendGridApiKey = "";
var sendGridApiUser = "";
// Create the email object first, and then add the properties.
var myMessage = new SendGridMessage();
// Add the message properties.
myMessage.From = new MailAddress("[email protected]m");
// Add customer's email addresses to the To field.
myMessage.AddTo(order.Email);
myMessage.Subject = "Contoso Sports League order received";
// Add the HTML and Text bodies.
myMessage.Html = "";
myMessage.Text = "";
// Add our generated PDF receipt as an attachment.
using (var stream = new MemoryStream(file))
{
myMessage.AddAttachment(stream, fileName);
}
var credentials = new NetworkCredential(sendGridApiUser, sendGridApiKey);
// Create a Web transport using our SendGrid API user and key.
var transportWeb = new Web(credentials);
// Send the email.
transportWeb.DeliverAsync(myMessage);
}
示例2: CreateMimeMessage
public void CreateMimeMessage()
{
var message = new SendGridMessage();
var attachment = Path.GetTempFileName();
var text = "this is a test";
var html = "<b>This<\b> is a better test";
var headers = new KeyValuePair<String, String>("custom", "header");
message.AddAttachment(attachment);
message.Text = text;
message.Html = html;
message.AddTo("[email protected]");
message.From = new MailAddress("[email protected]");
message.AddHeaders(new Dictionary<string, string> {{headers.Key, headers.Value}});
message.EnableGravatar();
var mime = message.CreateMimeMessage();
var sr = new StreamReader(mime.AlternateViews[0].ContentStream);
var result = sr.ReadToEnd();
Assert.AreEqual(text, result);
sr = new StreamReader(mime.AlternateViews[1].ContentStream);
result = sr.ReadToEnd();
Assert.AreEqual(html, result);
result = mime.Headers.Get(headers.Key);
Assert.AreEqual(headers.Value, result);
result = mime.Headers.Get("X-Smtpapi");
var expected = "{\"filters\" : {\"gravatar\" : {\"settings\" : {\"enable\" : \"1\"}}}}";
Assert.AreEqual(expected, result);
result = mime.Attachments[0].Name;
Assert.AreEqual(Path.GetFileName(attachment), result);
}
示例3: GenerateProspectiveMailMessage
/// <summary>
/// Creates a MailMessage for the current MailAttribute instance.
/// </summary>
protected SendGridMessage GenerateProspectiveMailMessage(MailAttributes mail)
{
// Basic message attributes
var message = new SendGridMessage
{
From = mail.From,
To = mail.To.ToArray(),
Cc = mail.Cc.ToArray(),
Bcc = mail.Bcc.ToArray(),
ReplyTo = mail.ReplyTo.ToArray(),
Subject = mail.Subject,
Headers = (Dictionary<string, string>)mail.Headers
};
// Message content
foreach (var view in mail.AlternateViews)
{
var reader = new StreamReader(view.ContentStream);
var body = reader.ReadToEnd();
if (view.ContentType.MediaType == MediaTypeNames.Text.Plain)
{
message.Text = body;
}
if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
{
message.Html = body;
}
}
// Attachments
foreach (
var mailAttachment in
mail.Attachments.Select(
attachment =>
AttachmentCollection.ModifyAttachmentProperties(attachment.Key, attachment.Value, false)))
{
using (var stream = new MemoryStream())
{
stream.Seek(0, SeekOrigin.Begin);
mailAttachment.ContentStream.CopyTo(stream);
message.AddAttachment(stream, mailAttachment.Name);
}
}
return message;
}
示例4: AddAttachments
internal static SendGridMessage AddAttachments(SendGridMessage message, string[] attachments)
{
if (attachments != null)
{
foreach (string file in attachments)
{
if (!String.IsNullOrWhiteSpace(file))
{
if (File.Exists(file))
{
using (var stream = new FileStream(file, FileMode.Open))
{
message.AddAttachment(stream, Path.GetFileName(file));
}
}
}
}
}
return message;
}
示例5: Test_EmbedImage_listlinkedresource
public void Test_EmbedImage_listlinkedresource()
{
var filename = new string[] { Path.GetTempFileName(), Path.GetTempFileName() };
var attachments = filename.ToList().ConvertAll<Attachment>((x) => { return new Attachment(x); });
var linkedResources = filename.ToList().ConvertAll<LinkedResource>((x) => { return new LinkedResource(x); });
var mail = BasicMailBuilder
.EmbedImages(linkedResources)
.Build();
var message = new SendGridMessage();
message.AddAttachment(attachments[0].ContentStream, attachments[0].Name);
message.AddAttachment(attachments[1].ContentStream, attachments[1].Name);
message.EmbedImage(linkedResources[0].ContentId, linkedResources[0].ContentId);
message.EmbedImage(linkedResources[1].ContentId, linkedResources[1].ContentId);
CollectionAssert.AreEquivalent(message.GetEmbeddedImages().ToList(), mail.GetEmbeddedImages().ToList());
Assert.AreEqual(2, message.StreamedAttachments.Count);
Assert.AreEqual(2, mail.StreamedAttachments.Count);
Assert.AreEqual(message.StreamedAttachments.First().Value.Length, mail.StreamedAttachments.First().Value.Length);
Assert.AreEqual(message.StreamedAttachments.Last().Value.Length, mail.StreamedAttachments.Last().Value.Length);
}
示例6: Test_EmbedImage_linkedresourcecollection
public void Test_EmbedImage_linkedresourcecollection()
{
var filename = Path.GetTempFileName();
var attachment = new Attachment(filename);
var av = AlternateView.CreateAlternateViewFromString("Testing");
av.LinkedResources.Add(new LinkedResource(filename));
var mail = BasicMailBuilder
.EmbedImages(av.LinkedResources)
.Build();
var message = new SendGridMessage();
message.AddAttachment(attachment.ContentStream, attachment.Name);
message.EmbedImage(av.LinkedResources[0].ContentId, av.LinkedResources[0].ContentId);
CollectionAssert.AreEquivalent(message.GetEmbeddedImages().ToList(), mail.GetEmbeddedImages().ToList());
Assert.AreEqual(1, message.StreamedAttachments.Count);
Assert.AreEqual(1, mail.StreamedAttachments.Count);
Assert.AreEqual(message.StreamedAttachments.First().Value.Length, mail.StreamedAttachments.First().Value.Length);
}
示例7: Test_EmbedImage_linkedresource
public void Test_EmbedImage_linkedresource()
{
var filename = Path.GetTempFileName();
var attachment = new Attachment(filename);
var linkedResource = new LinkedResource(filename);
var mail = BasicMailBuilder
.EmbedImage(linkedResource)
.Build();
var message = new SendGridMessage();
message.AddAttachment(attachment.ContentStream, attachment.Name);
message.EmbedImage(linkedResource.ContentId, linkedResource.ContentId);
CollectionAssert.AreEquivalent(message.GetEmbeddedImages().ToList(), mail.GetEmbeddedImages().ToList());
Assert.AreEqual(1, message.StreamedAttachments.Count);
Assert.AreEqual(1, mail.StreamedAttachments.Count);
Assert.AreEqual(message.StreamedAttachments.First().Value.Length, mail.StreamedAttachments.First().Value.Length);
}
示例8: Test_EmbedImage_filepath_cid
public void Test_EmbedImage_filepath_cid()
{
var filename = Path.GetTempFileName();
var cid = "[email protected]";
var mail = BasicMailBuilder
.EmbedImage(filename, cid)
.Build();
var message = new SendGridMessage();
message.AddAttachment(filename);
message.EmbedImage(new FileInfo(filename).Name, cid);
CollectionAssert.AreEquivalent(message.GetEmbeddedImages().ToList(), mail.GetEmbeddedImages().ToList());
CollectionAssert.AreEquivalent(message.Attachments, mail.Attachments);
CollectionAssert.AreEquivalent(message.StreamedAttachments, mail.StreamedAttachments);
}
示例9: Test_AttachFile_stream_filename
public void Test_AttachFile_stream_filename()
{
var filename = Path.GetTempFileName();
var attachment = new Attachment(filename);
var mail = BasicMailBuilder
.AttachFile(attachment.ContentStream, attachment.Name)
.Build();
var message = new SendGridMessage();
message.AddAttachment(attachment.ContentStream, attachment.Name);
Assert.AreEqual(1, message.StreamedAttachments.Count);
Assert.AreEqual(1, mail.StreamedAttachments.Count);
Assert.IsTrue(message.StreamedAttachments.ContainsKey(attachment.Name));
Assert.IsTrue(mail.StreamedAttachments.ContainsKey(attachment.Name));
Assert.AreEqual(message.StreamedAttachments[attachment.Name].Length, mail.StreamedAttachments[attachment.Name].Length);
}
示例10: Test_AttachFile_listattachment
public void Test_AttachFile_listattachment()
{
var filenames = new string[] { Path.GetTempFileName(), Path.GetTempFileName() };
List<Attachment> attachments = filenames.ToList().ConvertAll<Attachment>((x) => { return new Attachment(x); });
var mail = BasicMailBuilder
.AttachFiles(attachments)
.Build();
var message = new SendGridMessage();
message.AddAttachment(attachments[0].ContentStream, attachments[0].Name);
message.AddAttachment(attachments[1].ContentStream, attachments[1].Name);
Assert.AreEqual(2, message.StreamedAttachments.Count);
Assert.AreEqual(2, mail.StreamedAttachments.Count);
Assert.IsTrue(message.StreamedAttachments.ContainsKey(attachments[0].Name));
Assert.IsTrue(message.StreamedAttachments.ContainsKey(attachments[1].Name));
Assert.IsTrue(mail.StreamedAttachments.ContainsKey(attachments[0].Name));
Assert.IsTrue(mail.StreamedAttachments.ContainsKey(attachments[1].Name));
Assert.AreEqual(message.StreamedAttachments[attachments[0].Name].Length, mail.StreamedAttachments[attachments[0].Name].Length);
Assert.AreEqual(message.StreamedAttachments[attachments[1].Name].Length, mail.StreamedAttachments[attachments[1].Name].Length);
}
示例11: Test_AttachFile_filepath
public void Test_AttachFile_filepath()
{
var filename = Path.GetTempFileName();
var mail = BasicMailBuilder
.AttachFile(filename)
.Build();
var message = new SendGridMessage();
message.AddAttachment(filename);
CollectionAssert.AreEquivalent(message.Attachments, mail.Attachments);
CollectionAssert.AreEquivalent(message.StreamedAttachments, mail.StreamedAttachments);
}
示例12: CreateSendGridMessage
private SendGridMessage CreateSendGridMessage(string emailTo, string emailFrom, string name, string message, List<UploadedFile> files, ClientSetting clientSettings, bool autoReply = false)
{
// Create the email object first, then add the properties.
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo(emailTo);
myMessage.From = new MailAddress(emailFrom, name);
myMessage.Subject = autoReply ? clientSettings.AutoReplySubjectLine : clientSettings.SubjectLine;
myMessage.Html = message;
if (clientSettings.EnableFileUpload && !autoReply)
{
foreach (var file in files)
{
myMessage.AddAttachment(new MemoryStream(file.FileBytes), file.FileName);
}
}
return myMessage;
}
示例13: Send
//Note that at the moment, we actually are submitting through SendGrid, not Gmail.
public async void Send(EnvelopeDO envelope)
{
if (envelope == null)
throw new ArgumentNullException("envelope");
if (!string.Equals(envelope.Handler, EnvelopeDO.SendGridHander, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(@"This envelope should not be handled with Gmail.", "envelope");
if (envelope.Email == null)
throw new ArgumentException(@"This envelope has no Email.", "envelope");
if (envelope.Email.Recipients.Count == 0)
throw new ArgumentException(@"This envelope has no recipients.", "envelope");
var email = envelope.Email;
if (email == null)
throw new ArgumentException(@"Envelope email is null", "envelope");
try
{
var fromName = !String.IsNullOrWhiteSpace(email.FromName) ? email.FromName : email.From.Name;
var mailMessage = new SendGridMessage { From = new MailAddress(email.From.Address, fromName) };
if (!String.IsNullOrWhiteSpace(email.ReplyToAddress))
{
mailMessage.ReplyTo = new[] { new MailAddress(email.ReplyToAddress, email.ReplyToName) };
}
mailMessage.To = email.To.Select(toEmail => new MailAddress(toEmail.Address, toEmail.NameOrAddress())).ToArray();
mailMessage.Bcc = email.BCC.Select(bcc => new MailAddress(bcc.Address, bcc.NameOrAddress())).ToArray();
mailMessage.Cc = email.CC.Select(cc => new MailAddress(cc.Address, cc.NameOrAddress())).ToArray();
mailMessage.Subject = email.Subject;
if ((email.PlainText == null || email.HTMLText == null) && string.IsNullOrEmpty(envelope.TemplateName))
{
throw new ArgumentException("Trying to send an email that doesn't have both an HTML and plain text body");
}
if (email.PlainText == null || email.HTMLText == null)
{
mailMessage.Html = "<html></html>";
mailMessage.Text = "";
}
else
{
mailMessage.Html = email.HTMLText;
mailMessage.Text = email.PlainText;
}
var headers = new Dictionary<String, String>();
if (!String.IsNullOrEmpty(email.MessageID))
headers.Add("Message-ID", email.MessageID);
if (!String.IsNullOrEmpty(email.References))
headers.Add("References", email.References);
if (headers.Any())
mailMessage.AddHeaders(headers);
foreach (var attachment in email.Attachments)
{
mailMessage.AddAttachment(attachment.GetData(), attachment.OriginalName);
}
if (!string.IsNullOrEmpty(envelope.TemplateName))
{
mailMessage.EnableTemplateEngine(envelope.TemplateName);//Now TemplateName will be TemplateId on Sendgrid.
if (envelope.MergeData != null)
{
//Now, we need to do some magic.
//Basically - we need the length of each substitution to match the length of recipients
//In our case, most of the time, all the substitutions are the same, except for token-related fields
//To make it easier to use, we attempt to pad out the substition arrays if they lengths don't match
//We only do that if we're given a string value. In any other case, we allow sengrid to fail.
var subs = new Dictionary<String, List<String>>();
foreach (var pair in envelope.MergeData)
{
var arrayType = pair.Value as JArray;
List<String> listVal;
if (arrayType != null)
{
listVal = arrayType.Select(a => a.ToString()).ToList();
}
else
{
listVal = new List<string>();
for (var i = 0; i < email.Recipients.Count(); i++) //Pad out the substitution
listVal.Add(pair.Value == null ? String.Empty : pair.Value.ToString());
}
subs.Add(pair.Key, listVal);
}
foreach(var sub in subs)
mailMessage.AddSubstitution(sub.Key, sub.Value);
}
}
try
{
await _transport.DeliverAsync(mailMessage);
//.........这里部分代码省略.........
示例14: SendSendGridEmail
/// <summary>
/// This function will send the email via SendGrid.
/// </summary>
/// <param name="kMessage">MailMessage - Message object to send</param>
protected void SendSendGridEmail(MailMessage kMessage)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append("Date:");
sb.AppendLine();
sb.Append(DateTime.Now.ToString());
sb.AppendLine();
// Create the email object first, then add the properties.
var sgMessage = new SendGridMessage();
// Add the message properties.
sgMessage.From = new MailAddress(kMessage.From.ToString());
sb.Append("From:");
sb.AppendLine();
sb.Append(sgMessage.From.Address);
sb.AppendLine();
// Add multiple addresses to the To field.
sb.Append("To:");
sb.AppendLine();
foreach (MailAddress address in kMessage.To)
{
sgMessage.AddTo(address.Address);
sb.Append(address.Address + ";");
}
sb.AppendLine();
sgMessage.Subject = kMessage.Subject;
sb.Append("Subject:");
sb.AppendLine();
sb.Append(sgMessage.Subject);
sb.AppendLine();
// HTML & plain-text
if (kMessage.AlternateViews.Count > 0)
{
foreach (AlternateView view in kMessage.AlternateViews)
{
// Position must be reset first
if (view.ContentStream.CanSeek)
{
view.ContentStream.Position = 0;
}
using (StreamWrapper wrappedStream = StreamWrapper.New(view.ContentStream))
{
using (StreamReader reader = StreamReader.New(wrappedStream))
{
if (view.ContentType.MediaType == MediaTypeNames.Text.Html)
{
sgMessage.Html = reader.ReadToEnd();
}
else if (view.ContentType.MediaType == MediaTypeNames.Text.Plain)
{
sgMessage.Text = reader.ReadToEnd();
}
}
}
}
}
sb.Append("Body:");
if (ValidationHelper.GetString(sgMessage.Html, "") != "")
{
sb.Append(sgMessage.Html);
}
else
{
sb.Append(sgMessage.Text);
}
sb.AppendLine();
//Handle any attachments
sb.Append("Attachments:");
sb.AppendLine();
foreach (Attachment attachment in kMessage.Attachments)
{
sgMessage.AddAttachment(attachment.ContentStream, attachment.Name);
sb.Append(attachment.Name);
sb.AppendLine();
}
//Enable click tracking
sgMessage.EnableClickTracking(true);
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential("[SendGridLogin]", "[SendGridPassword]");
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
transportWeb.Deliver(sgMessage);
//.........这里部分代码省略.........
示例15: ConfirmRegistration
public static void ConfirmRegistration(int registrationId, string reportpath)
{
var context = new CourseContext();
var registration = context.Registrations.Include("Courses").FirstOrDefault(r => r.Id == registrationId);
if (registration != null)
{
var myMessage = new SendGridMessage();
myMessage.AddTo(registration.EMail);
myMessage.AddTo("[email protected]");
myMessage.From = new MailAddress("[email protected]", "Fahrschule Grütter-Stooss");
var stream = new MemoryStream();
var report = ReportHelper.GetReportFromFile(reportpath);
report.ReportParameters["RegistrationId"].Value = registrationId;
var reportProcessor = new Telerik.Reporting.Processing.ReportProcessor();
var renderingResult = reportProcessor.RenderReport("PDF", report, null);
stream.Write(renderingResult.DocumentBytes, 0, renderingResult.DocumentBytes.Length);
stream.Position = 0;
myMessage.AddAttachment(stream, "Anmeldung.pdf");
myMessage.Subject = "Bestätigung Deiner Anmeldung";
if (registration.Courses.Count == 1)
{
var course = registration.Courses.ElementAt(0);
myMessage.Text = string.Format("Für den Kurs {0} am {1}", course.Name, course.StartDateTime);
}
if (registration.Courses.Count > 1)
{
var sb = new StringBuilder();
sb.AppendLine("Für die Kurse:");
foreach (var course in registration.Courses)
{
sb.AppendLine(string.Format("Für den Kurs {0} am {1}", course.Name, course.StartDateTime));
myMessage.Text = sb.ToString();
}
}
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential("[email protected]",
"[email protected]");
// Create an Web transport for sending email, using credentials...
//var transportWeb = new Web(credentials);
// ...OR create a Web transport, using API Key (preferred)
var transportWeb = new Web("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");
// Send the email.
transportWeb.DeliverAsync(myMessage);
}
}