Send emails using the SharePoint SMTP Mail Service

Friday, 6 March 2009 15:03 by myro
[Update] 

As blogtech said you can send mails by calling the SharePoint' SMTP Mail Service directly from the SPUtility object:


SPUtility.SendEmail
msdn.microsoft.com/.../...sputility.sendemail.aspx

but if you want to send your mails using normal ASP.NET SMTP functions, get the SMTP address in this way:

[Old post] 

Here's a small method witten in c# to let you send send mails using your SharePoint's Mail Service

public static bool SendMail(string Subject, string Body,
            bool IsBodyHtml, string From, string To, string Cc, string Bcc)
{
    bool mailSent= false;
    try
    {
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Host = SPContext.Current.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
        MailMessage mailMessage = new MailMessage(From, To, Subject, Body);
        if (!String.IsNullOrEmpty(Cc))
        {
            MailAddress CCAddress = new MailAddress(Cc);
            mailMessage.CC.Add(CCAddress);
        }
        if (!String.IsNullOrEmpty(Bcc))
        {
            MailAddress BCCAddress = new MailAddress(Bcc);
            mailMessage.Bcc.Add(BCCAddress);
        }

        mailMessage.IsBodyHtml = IsBodyHtml;
        smtpClient.Send(mailMessage);
        mailSent = true;
    }
    catch (Exception) { return mailSent; }

    return mailSent;
}

If you are not working in a SharePoint context, get the SPWebApplicazion reference from a new SPSite

static string GetSharePointMailService(string siteUrl)
{
    string address = string.Empty;
    using (SPSite site = new SPSite(siteUrl))
    {
      address = site.WebApplication.OutboundMailServiceInstance.Server.Address;
    }
    return address;
}

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   , ,
Categories:   .NET | SharePoint 2007
Actions:   Bookmark and Share | Permalink | Comments (3) | Comment RSSRSS comment feed
If you consider this post usefull for your purposes, please consider visiting my sponsors to help me out with the myrocode.com maintenance. Thank you.

Comments