SPUtility Sending Email with display name
Question
I'm writing a timer job which once complete it sends out an email from noreply@company.com
, when it arrives in outlook it shows that address as the from person.
Is there a way to get it to display a 'display name'. For example all emails received from me would show Paul Matthews
not paul.matthews@company.com
. (Which I know in this instance is probably more to do with AD and Exchange).
The code I'm using is below.
var emailFromAddress = _properties["EmailFromAddress"].ToString();
var emailToAddress = _properties["EmailDistributionGroup"].ToString();
var webAddress = _properties["WebSiteOfLibrary"].ToString();
var subject = "New Report - " + DateTime.Now.ToString("dd MMM yyyy");
StringDictionary messageHeader = new StringDictionary();
messageHeader.Add("to", emailToAddress);
messageHeader.Add("from", emailFromAddress);
messageHeader.Add("subject", subject);
messageHeader.Add("content-type", "text/html");
using (SPSite site = new SPSite(webAddress))
{
using (SPWeb web = site.OpenWeb())
{
DateTime timeNow = DateTime.Now;
var sb = new StringBuilder();
sb.Append(
"<STYLE TYPE='text/css'>body, html{font-color:#000;font-family:arial;font-size:8.0pt}</STYLE>");
sb.AppendFormat("<div style='font-size:11pt;font-family:calibri'>Results between {0} and {1}</div><br/><br/>", LastRun.ToString("dd MMM yyyy hh:mm tt"), timeNow.ToString("dd MMM yyyy h:mm tt"));
sb.AppendFormat("<div style='font-size:11pt;font-family:calibri'>Total: {0}<br/><br/>", total);
sb.AppendLine(HTMLResults);
SPUtility.SendEmail(web, messageHeader, sb.ToString());
}
}
The thing is, the email address has to be noreply@company.com which we will use this for multiple applications, so the display name should reflect a name of the application.
Solution
Might I suggest switching to using the System.Net.Mail.MailMessage object instead of SPUtility. SPUtility.SendEmail
is a good shortcut but, as you've seen, you lose a lot of control over how the message is sent and formatted. The MailMessage
object gives you that back but does require just a tiny bit more work.
To answer your specific question, the MailAddress object handles the formatting of the email address and name combination so you would have to use your application name as the 'fromname
' below.
MailMessage msg = new MailMessage();
msg.From = new MailAddress(web.Site.WebApplication.OutboundMailSenderAddress, fromName);
msg.To.Add(new MailAddress(to));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
SmtpClient server = new SmtpClient(web.Site.WebApplication.OutboundMailServiceInstance.Server.Address);
server.Send(msg);
OTHER TIPS
If you want to customize the sender email address, then you cannot use SPUtility.SendEmail -- you'll have to use the System.Net.Mail framework classes.
Under the covers, SPUtility calls a method named "RemoveFriendlyNameFromEmailAddress" :(