Wednesday, January 25, 2012

sharepoint send email with attachment

While we working with SMTP in sharepoint projects. It is mandatory to provide SMTP server name to send emails or we can use SPUtility.SendMail().

But it is strongly recommended to use Object model for getting SMTP server name for good coding practice.

Below is the peace of code to do the same :

string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;

string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

MailMessage message = new MailMessage(smtpFrom, "");

message.Subject = "Happy Birthday";

WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultNetworkCredentials;

string imagePath = web.Url + "/_layouts/images/BirthdayImage.gif";
LinkedResource image1 = new LinkedResource(SPUtility.GetGenericSetupPath("TEMPLATE\\LAYOUTS\\IMAGES\\BirthdayImage.gif"));

image1.ContentId = "birthdayimage";

AlternateView avHtml = AlternateView.CreateAlternateViewFromString("
" + "Have a blast with frineds and family!!! Have a great day!!!", null, MediaTypeNames.Text.Html);



message.IsBodyHtml = true;

SmtpClient smtpClient = new SmtpClient(smtpServer);

Happy coding !!!

No comments:

Post a Comment