I am not sure why but Microsoft does it every time. They give you a piece of functionality but leaves you struggling with a certain and so called ‘known’ limitation.
One such limitation is sending emails when using SharePoint. SharePoint provides an API called ‘SPUtility.SendEmail‘ to send emails. But the implementation of this API seems to be incomplete. If you notice the method, it is impossible to send an email with an attachment or to change the from address of the sender.
To make thing simpler, you can use the following class to extend the functionality and use the good old MailMessage object to send email (without any extra infrastructure configuration).
public class SMTPHelper
{
private readonly string _specifiedPickupDirectory = string.Empty;
private readonly SmtpClient _smtpClient;
public SMTPHelper(string specifiedPickupDirectory)
{
_specifiedPickupDirectory = specifiedPickupDirectory;
_smtpClient = new SmtpClient();
if (string.IsNullOrEmpty(_specifiedPickupDirectory))
{
//Get the Sharepoint SMTP information from the SPAdministrationWebApplication
var host = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
_smtpClient.Host = host;
}
else
{
_smtpClient.PickupDirectoryLocation = _specifiedPickupDirectory;
_smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
}
}
public void SendEmail(MailMessage mailMessage)
{
_smtpClient.Send(mailMessage);
}
}
The above code basically make use of the OutboundMailServiceInstance to retrieve the SMTP server address configured within SharePoint. Generally, you can configure this address in Central Administration -> System Settings -> Configure outgoing e-mail settings.
Be First to Comment