Being Asp.Net developers, we all know we can send email from within custom code using the virtual SMPT server running on the Web Front End server where our code is running, but what if you want to use the same SMTP/Exchange settings you configured in Central Administration?
Luckily, there's a way to do so.
I like to create an object I call SPEmail for encapsulation, then within the Send method go dig for the info I need from the SPAdministrationWebApplication.Local and it's OutboundMailServerInstance property. Once you have these objects, the information entered in Central Admin can be obtained and be used to set up the standard System.Net.Mail SmtpClient and MailMessage objects.
No messing with the web.config file. Nice.
Here's the code for my SPEmail object:
public class SPEmail
{
#region Constructors
public SPEmail() { }
#endregion
#region Private Members
string _To = string.Empty;
string _Subject = string.Empty;
string _Body = string.Empty;
bool _HTML = false;
#endregion
#region Public Properties
public string To
{
get
{
return this._To;
}
set
{
this._To = value;
}
}
public string Subject
{
get
{
return this._Subject;
}
set
{
this._Subject = value;
}
}
public string Body
{
get
{
return this._Body;
}
set
{
this._Body = value;
}
}
public bool IsHtml
{
get
{
return this._HTML;
}
set
{
this._HTML = value;
}
}
#endregion
public void Send()
{
string smtp = string.Empty;
string fromAddress = string.Empty;
string replyToAddress = string.Empty;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPAdministrationWebApplication adminApp = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local;
SPOutboundMailServiceInstance emailService = adminApp.OutboundMailServiceInstance;
smtp = emailService.Server.Address;
fromAddress = adminApp.OutboundMailSenderAddress;
replyToAddress = adminApp.OutboundMailReplyToAddress;
if (!string.IsNullOrEmpty(this.To))
{
SmtpClient mail = new SmtpClient();
MailMessage message = new MailMessage();
message.From = new MailAddress(fromAddress);
message.To.Add(this.To);
if (!string.IsNullOrEmpty(replyToAddress))
message.ReplyTo = new MailAddress(replyToAddress);
if (!string.IsNullOrEmpty(this.Subject))
message.Subject = this.Subject;
if (!string.IsNullOrEmpty(this.Body))
message.Body = this.Body;
message.IsBodyHtml = this.IsHtml;
mail.Host = smtp;
mail.Send(message);
}
});
}
}
So - if you want to write your own, there you go!
Sigh...
After I put this together, I found that you can send email from within the SPUtility object. SPUtility.SendEmail() will take care of all this for you, too.