Skip to content

Commit 1712500

Browse files
Merge pull request #458 from JefStat/StringToEmailAddress
Add a StringToEmailAddress helper function
2 parents 7d31c3b + 619ffa5 commit 1712500

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/SendGrid/Helpers/Mail/MailHelper.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,19 @@
66
namespace SendGrid.Helpers.Mail
77
{
88
using System.Collections.Generic;
9+
using System.Text.RegularExpressions;
910

1011
/// <summary>
1112
/// Simplified email sending for common use cases
1213
/// </summary>
1314
public class MailHelper
1415
{
16+
private const string NameGroup = "name";
17+
private const string EmailGroup = "email";
18+
private static readonly Regex Rfc2822Regex = new Regex(
19+
$@"(?:(?<{NameGroup}>)(?<{EmailGroup}>[^\<]*@.*[^\>])|(?<{NameGroup}>[^\<]*)\<(?<{EmailGroup}>.*@.*)\>)",
20+
RegexOptions.ECMAScript);
21+
1522
/// <summary>
1623
/// Send a single simple email
1724
/// </summary>
@@ -121,5 +128,23 @@ public static SendGridMessage CreateMultipleEmailsToMultipleRecipients(
121128

122129
return msg;
123130
}
131+
132+
/// <summary>
133+
/// Uncomplex conversion of a <![CDATA["Name <[email protected]>"]]> to EmailAddress
134+
/// </summary>
135+
/// <param name="rfc2822Email">"[email protected]" or <![CDATA["Name <[email protected]>"]]> string</param>
136+
/// <returns>EmailsAddress Object</returns>
137+
public static EmailAddress StringToEmailAddress(string rfc2822Email)
138+
{
139+
var match = Rfc2822Regex.Match(rfc2822Email);
140+
if (!match.Success)
141+
{
142+
return new EmailAddress(rfc2822Email);
143+
}
144+
145+
var email = match.Groups[EmailGroup].Value.Trim();
146+
var name = match.Groups[NameGroup].Value.Trim();
147+
return new EmailAddress(email, name);
148+
}
124149
}
125-
}
150+
}

tests/SendGrid.Tests/Integration.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6037,4 +6037,18 @@ public override HttpResponseMessage Send(HttpRequestMessage request)
60376037
throw new TimeoutException(exceptionMessage);
60386038
}
60396039
}
6040+
6041+
public class MailHelperTests
6042+
{
6043+
[Theory]
6044+
[InlineData("Name Of A Person+", "[email protected]", "Name Of A Person+ < [email protected] > ")]
6045+
[InlineData("", "[email protected]", " [email protected] ")]
6046+
[InlineData(null, "notAValidEmail", "notAValidEmail")]
6047+
public void StringToEmail(string expectedName, string expectedEmail, string rf2822Email)
6048+
{
6049+
var address = MailHelper.StringToEmailAddress(rf2822Email);
6050+
Assert.Equal(expectedEmail, address.Email);
6051+
Assert.Equal(expectedName, address.Name);
6052+
}
6053+
}
60406054
}

0 commit comments

Comments
 (0)