Pages

Showing posts with label sending emails. Show all posts
Showing posts with label sending emails. Show all posts

Saturday, July 25, 2009

How to Send Email from SharePoint object model by accessing Email Configuration from Central Admin

Here is example code for sending email from SharePoint object model, main part of code would be “SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address”, it will return mail server address which is assigned from SharePoint central administration site as per web application

Sample Code:
,

private void SendEmail()
{
try
{
SmtpClient client = LoadSmtpInformation();
client.Send(BuildMailMessage());
}
catch (Exception Ex)
{
Response.Write(Ex.Message);
}
}

private SmtpClient LoadSmtpInformation()
{

string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
SmtpClient client = new SmtpClient(smtpServer);
client.UseDefaultCredentials = true;
return client;
}

private MailMessage BuildMailMessage()
{

MailMessage message = new MailMessage();

message.From = new MailAddress(SPContext.Current.Web.CurrentUser.Email);
message.To.Add(new MailAddress(User.Email));
message.IsBodyHtml = true;
message.Body = “Email Message”;

message.Subject = "Subject of Email";
return message;

}