Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closes #266 #746

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
language: csharp
dotnet: 1.0.4
dotnet: 2.1
os: linux
dist: trusty
mono: latest
Expand All @@ -24,9 +24,10 @@ before_script:
script:
- dotnet restore
- dotnet build ./src/SendGrid -c Release
- dotnet test ./tests/SendGrid.Tests/SendGrid.Tests.csproj -c Release -f netcoreapp1.0
- dotnet test ./tests/SendGrid.Tests/SendGrid.Tests.csproj -c Release -f netcoreapp2.0
- ls ./src/SendGrid/bin/Release/net452/
- ls ./src/SendGrid/bin/Release/netstandard1.3/
- ls ./src/SendGrid/bin/Release/netstandard2.0/
- dotnet pack ./src/SendGrid -c Release
- curl -s https://codecov.io/bash > .codecov
- chmod +x .codecov
Expand Down
137 changes: 137 additions & 0 deletions src/SendGrid/Helpers/Mail/MailMessageExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// <copyright file="MailMessageExtensions.cs" company="SendGrid">
// Copyright (c) SendGrid. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
#if NETSTANDARD2_0 || NET452

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;

namespace SendGrid.Helpers.Mail
{
/// <summary>
/// A collection of extension to assist with the conversion of System.Net.Mail.MailMessage to <see cref="SendGridMessage"/>
/// </summary>
public static class MailMessageExtensions
{
/// <summary>
/// Converts a System.Net.Mail.MailAddress to a sendgrid address
/// </summary>
/// <param name="address">The address to be converted</param>
/// <returns>The result of the conversion</returns>
public static EmailAddress ToSendGridAddress(this MailAddress address)
{
return string.IsNullOrWhiteSpace(address.DisplayName) ?
new EmailAddress(address.Address) :
new EmailAddress(address.Address, address.DisplayName.Replace(",", string.Empty).Replace(";", string.Empty));
}

/// <summary>
/// Copies the attachment from a MailMessage into the <see cref="SendGridMessage"/> object as a base64 string.
/// </summary>
/// <param name="attachment">The attachment to be converted</param>
/// <returns>Returns a <see cref="Attachment"/></returns>
public static SendGrid.Helpers.Mail.Attachment ToSendGridAttachment(this System.Net.Mail.Attachment attachment)
{
using (var stream = new MemoryStream())
{
attachment.ContentStream.CopyTo(stream);
return new SendGrid.Helpers.Mail.Attachment()
{
Disposition = "attachment",
Type = attachment.ContentType.MediaType,
Filename = attachment.Name,
ContentId = attachment.ContentId,
Content = Convert.ToBase64String(stream.ToArray())
};
}
}

/// <summary>
/// Converts a System.Net.Mail.MailMessage to a SendGrid message.
/// </summary>
/// <param name="message">The MailMessage to be converted</param>
/// <returns>Returns a <see cref="SendGridMessage"/> with the properties from the MailMessage</returns>
public static SendGridMessage ToSendGridMessage(this MailMessage message)
{
var sendgridMessage = new SendGridMessage();

sendgridMessage.From = ToSendGridAddress(message.From);

if (message.ReplyToList.Any())
{
if (message.ReplyToList.Count > 1)
{
throw new ArgumentException("Sendgrid only supports one reply to address.");
}

sendgridMessage.ReplyTo = message.ReplyToList.Single().ToSendGridAddress();
}

if (message.To.Any())
{
var tos = message.To.Select(ToSendGridAddress).ToList();
sendgridMessage.AddTos(tos);
}

if (message.CC.Any())
{
var cc = message.CC.Select(ToSendGridAddress).ToList();
sendgridMessage.AddCcs(cc);
}

if (message.Bcc.Any())
{
var bcc = message.Bcc.Select(ToSendGridAddress).ToList();
sendgridMessage.AddBccs(bcc);
}

if (!string.IsNullOrWhiteSpace(message.Subject))
{
sendgridMessage.Subject = message.Subject;
}

if (message.Headers.Count > 0)
{
var headers = message.Headers.AllKeys.ToDictionary(x => x, x => message.Headers[x]);
sendgridMessage.AddHeaders(headers);
}

if (!string.IsNullOrWhiteSpace(message.Body))
{
var content = message.Body;

if (message.IsBodyHtml)
{

if (content.StartsWith("<html"))
{
content = message.Body;
}
else
{
content = $"<html><body>{message.Body}</body></html>";
}

sendgridMessage.AddContent("text/html", content);
}
else
{
sendgridMessage.AddContent("text/plain", content);
}
}

if (message.Attachments.Any())
{
sendgridMessage.Attachments = new List<Attachment>();
sendgridMessage.Attachments.AddRange(message.Attachments.Select(ToSendGridAttachment));
}

return sendgridMessage;
}
}
}
#endif
105 changes: 105 additions & 0 deletions tests/SendGrid.Tests/Helpers/Mail/MailMessageExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
using System.IO;
using System.Linq;
using System.Net.Mail;
using SendGrid.Helpers.Mail;
using Xunit;

namespace SendGrid.Tests.Helpers.Mail
{
public class MailMessageExtensionsTests
{
[Theory]
[InlineData("[email protected]")]
[InlineData("[email protected]")]
public void ConvertEmailAddresses(string email)
{
var address = new MailAddress(email).ToSendGridAddress();
Assert.Equal(email, address.Email);
}

[Theory]
[InlineData("[email protected]", "[email protected]", "Widget Factory Production", "Ben, widget production is down 15%, could you investigate?")]
public void TestSimpleMailMessageEmail(string from, string to, string subject, string body)
{
var mail = new MailMessage(from, to)
{
Subject = subject,

};

mail.Body = body;

var message = mail.ToSendGridMessage();

Assert.Equal(from, message.From.Email);
Assert.Equal(subject, message.Subject);
Assert.Contains(message.Personalizations.SelectMany(x => x.Tos), x => x.Email == to);
Assert.Contains(message.Contents, x => x.Value == body);
}

[Theory]
[InlineData("[email protected]", "[email protected]", "Widget Factory Production", "[email protected]", "[email protected]")]
public void TestMailMessageEmailWithCC(string from, string to, string subject, string cc, string bcc)
{
var mail = new MailMessage(from, to)
{
Subject = subject
};

mail.CC.Add(cc);
mail.Bcc.Add(bcc);

var message = mail.ToSendGridMessage();


Assert.Equal(from, message.From.Email);
Assert.Equal(subject, message.Subject);
Assert.Contains(message.Personalizations.SelectMany(x => x.Tos), x => x.Email == to);
Assert.Contains(message.Personalizations.SelectMany(x => x.Ccs), x => x.Email == cc);
Assert.Contains(message.Personalizations.SelectMany(x => x.Bccs), x => x.Email == bcc);
}

[Theory]
[InlineData("[email protected]", "[email protected]", "[email protected]")]
public void TestSimpleMailMessageReplyTo(string from, string to, string replyTo)
{
var mail = new MailMessage(from, to);
mail.ReplyToList.Add(replyTo);

var message = mail.ToSendGridMessage();

Assert.Equal(replyTo, message.ReplyTo.Email);
}

[Fact]
public void TestMailMessageShouldConvertAttachements()
{
var mail = new MailMessage("[email protected]", "[email protected]");
var data = new byte[] { 0x1, 0x2, 0x3, 0x4 };

SendGridMessage message = null;

using (var stream = new MemoryStream(data))
{
mail.Attachments.Add(new System.Net.Mail.Attachment(stream, "Example.pdf"));
message = mail.ToSendGridMessage();
}

Assert.NotEmpty(message.Attachments);
var attachment = message.Attachments.Single();
Assert.Equal("Example.pdf", attachment.Filename);
Assert.False(string.IsNullOrEmpty(attachment.Content));
}

[Fact]
public void TestMailMessageHeaderConverted()
{
var mail = new MailMessage("[email protected]", "[email protected]");
mail.Headers.Add("Example", "Example");

var message = mail.ToSendGridMessage();
var headers = message.Personalizations.SelectMany(x => x.Headers);
Assert.Contains(headers, x => x.Key == "Example" && x.Value == "Example");
}
}
}
4 changes: 2 additions & 2 deletions tests/SendGrid.Tests/SendGrid.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp1.0</TargetFramework>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyName>SendGrid.Tests</AssemblyName>
<PackageId>SendGrid.Tests</PackageId>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<RuntimeFrameworkVersion>1.0.4</RuntimeFrameworkVersion>
<RuntimeFrameworkVersion>2.0.9</RuntimeFrameworkVersion>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
Expand Down