Sending email for SharePoint, with/without attachment

One of great things we can do with Sharepoint is sending an email. The most easiest way is using SPUtility. This will work if you have set up Outgoing email in Central Admin.
outgoing email

private void SendEmail()
	// Build the email message headers
	StringDictionary headers = new StringDictionary();
	headers.Add("to", "");
	headers.Add("subject", "Item Records");	
	headers.Add("content-type", "text/html");
	// Send the email
		using (var elevatedSite = new SPSite(SPContext.Current.Site.ID))
			using (var elevatedWeb = elevatedSite.OpenWeb())
				SPUtility.SendEmail(elevatedWeb, headers, GetEmailBody());

private String GetEmailBody()
	StringBuilder sb = new StringBuilder();
	sb.Append(String.Format("<p>Below is the {1} records on {0:dd MMM yyyy HH:mm}.</p>", DateTime.Now, "Item List"));
	return sb.ToString();

One problem using this method is when we try to send email with attachments, SPUtiliy.SendEmail doensn’t support it. And the solution is System.Net.Mail. You should set up SMTP server on machine first to make it works. Here is the code:

private void SendEmailSMTP()
	// get smtp server from central admin
	SPWebApplication oWebApp = SPContext.Current.Site.WebApplication;
	// set mail message
	MailMessage message = new MailMessage();
	MailAddress from = new MailAddress(oWebApp.OutboundMailSenderAddress);
	message.From = from;
	message.To.Add(new MailAddress(""));	
	message.Subject = "Test email";
	message.IsBodyHtml = true;
	message.Body = "<b>This is test email with attachment.<b>";
	// add attachment
	var attachment = new Attachment("C:\file.csv");

	// send email
	SmtpClient mailClient = new SmtpClient(oWebApp.OutboundMainServiceInstance.Server.Name);
	mailClient.Host = webApp.OutboundMailServiceInstance.Server.Address;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s