Louis-Charles Gagnon Blog

Microsoft Azure, Office 365 and SharePoint Blog

Send an email with custom recipient ReplyTo and To in SharePoint 2013 via C#

In a recent development for a consulting client. In a custom page, we wanted to send an email with the from a given user and allow the user to reply to email directly to the given user.

We noticed that the reply-to email was the SharePoint Admin Email and not the from displayed in the email.

We tried:

//Set E-mail Header Variables
var messageHeaders = new StringDictionary
{
    {"to", emailTo},                     
    {"from", emailFrom},
    {"replyto", emailFrom},
    {"subject", emailSubject},
    {"content-type", "text/html"}
};

//Send Email by SharePoint
SPUtility.SendEmail(Web, messageHeaders, emailBody);

This did send an email, but the replyto is not overrided.

We used the .NET Send Email method to make this work.

This method retrieves the SharePoint Central Admin smtp server defined in the farm:

var smtpServer = SPContext.Current.Web.Site.WebApplication.OutboundMailServiceInstance.Server.Address;

With that information we can send the email as follow:

var message = new System.Net.Mail.MailMessage();
message.To.Add(emailTo);
message.Subject = emailSubject;
message.From = new System.Net.Mail.MailAddress(emailFrom);
message.Body = emailBody;
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpServer);
smtp.Send(message);



blog comments powered by Disqus