Friday, January 11, 2008

How To Get the SharePoint Default Mail Server/Sender

Couple of methods that will retrieve the default mail server and sender that your Sharepoint web app uses:

//get the server
private string GetSmtpServer()

{
SPWebApplicationCollection spWebApplicationCollection = SPWebService.ContentService.WebApplications;
SPOutboundMailServiceInstance smtpServer = new SPOutboundMailServiceInstance();

if (spWebApplicationCollection != null)
{
foreach (SPWebApplication spWebApplication in spWebApplicationCollection)
{
smtpServer = spWebApplication.OutboundMailServiceInstance;
return smtpServer.Server.Address;
}
}
return string.Empty;
}

 

//get the sender
private string GetDefaultSmtpSender()
{
SPWebApplicationCollection spWebApplicationCollection = SPWebService.ContentService.WebApplications;
string sender = default(System.String);
if (spWebApplicationCollection != null)
{
foreach (SPWebApplication spWebApplication in spWebApplicationCollection)
{
sender = spWebApplication.OutboundMailSenderAddress;
return sender;
}
}
return string.Empty;
}


 

//sample usage
private void SendEmail(string subject, string msg, string to, string cc)
{
MailAddress toAddress = new MailAddress(to, "Main Recipient");
MailAddress fromAddress = new MailAddress(DEFAULT_SENDER);
MailMessage newmail = new MailMessage(fromAddress, toAddress);

//check if we need to cc this to anyone
if (!string.IsNullOrEmpty(cc))
{
MailAddress ccAddress = new MailAddress(cc, "Secondary Recipient");
newmail.CC.Add(ccAddress);
}

newmail.IsBodyHtml = true;
newmail.Subject = subject;
newmail.Body = msg;
System.Net.Mail.SmtpClient mail = new SmtpClient(DEFAULT_MAIL_SERVER);
mail.Send(newmail);
}



By the way, Yaro posted this in this blog too :)

0 comments: