Thursday, 29 March 2012

Send email from SharePoint web part



protected void Button1_Click(object sender, EventArgs e)
{
try
{
MailAddress[] ma = { new MailAddress("mail@mail.com") };
SendEmail(ma, "hello world from C# ", "this is sp");
SendEmailFromSP("mail@mail.com", "hello subject from SP", "hello body");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

}


private void SendEmailFromSP(string address, string sub, string bd)
{
SPSite site = SPContext.Current.Site;
SPWeb thisWeb = site.OpenWeb();
string toField = address;
string subject = sub;
string body = bd;
bool success = SPUtility.SendEmail(thisWeb, true, true, toField, subject, body);
Console.WriteLine(success);
}

private void SendEmail(MailAddress[] masTo, string subject, string body)
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(SPContext.Current.Site.WebApplication.OutboundMailSenderAddress);
foreach (MailAddress ma in masTo)
mail.To.Add(ma);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
SmtpClient smtp = new SmtpClient(SPContext.Current.Site.WebApplication.OutboundMailServiceInstance.Server.Address);
smtp.UseDefaultCredentials = true;
smtp.Send(mail);
Label1.Text = "OK";
}
}

No comments:

Post a Comment