Hi All,
Got a new thing for me, to share with you all.
when you have to send email and attachment with it then its easy task, when attachment file is lying on your file system.
But, when Attachment is as URL format, then its a little problem , as directly ULR formats are not supported. In this case you have to go by Steam param method for Attachment.
We need to use WebClient class for the same. with UseDefaultCredentials property set as true.
Otherwise you will get error 401 (Un-Authorized)
Below is code snippet. you can direcly call this method. Good to go
public static void SendMailWithAttachment(SPWeb
web, string toAddress, string
ccAddress, string subject, string body,SPListItem
Itemattachment)
{
MailMessage objEmail = new
MailMessage();
MailAddress mailFrom = null;
SmtpClient smtp = null;
SPWebApplication webapp = web.Site.WebApplication;
mailFrom = new MailAddress("Admin@abc.com", "Admin");
objEmail.From = mailFrom;
// if toAddress Contains many email addresses seperated by ','
if (toAddress.Contains(","))
{
string[] tos = toAddress.Split(',');
for (int
i = 0; i < tos.Length; i++)
{
objEmail.To.Add(new MailAddress(tos[i]));
}
}
else
{
objEmail.To.Add(new MailAddress(toAddress));
}
// if ccAddress Contains many email addresses seperated by ','
if (!string.IsNullOrEmpty(ccAddress))
{
if (ccAddress.Contains(","))
{
string[] ccs = ccAddress.Split(',');
for (int
i = 0; i < ccs.Length; i++)
{
if (!string.IsNullOrEmpty(ccs[i]))
objEmail.CC.Add(new MailAddress(ccs[i]));
}
}
else
{
objEmail.CC.Add(new MailAddress(ccAddress));
}
}
objEmail.Body = body;
objEmail.Subject = subject;
objEmail.IsBodyHtml = true;
//Adding Attachments to the Email, Itemattachment is SPListItem which contains Attachments
foreach (string
fileName in Itemattachment.Attachments)
{
string attachPath= Itemattachment.Attachments.UrlPrefix + fileName;
WebClient webAttach = new WebClient();
webAttach.UseDefaultCredentials = true;
var stream =
webAttach.OpenRead(attachPath);
Attachment attached = new Attachment(stream,
fileName);
objEmail.Attachments.Add(attached);
}
smtp = new SmtpClient();
smtp.Host = webapp.OutboundMailServiceInstance.Server.Address;
smtp.Send(objEmail);
}
Thanks Nice post. Worked for me.
ReplyDeleteThanks Amit.
Delete