Tuesday, May 5, 2009

Web Services Function to Send Mail with Attachement

--WebConfig File Setting
<appSettings>
   <add key="SmtpServer" value="mail.test.net" />
   <add key="UserName" value="
test@test.net" />
   <add key="Password" value="123456" />
</appSettings>

[WebMethod Fucntion]

public bool SendMail(string FromAddress,string ToAddress,string BccAddress,string CcAddress,string Subject,string Attachment,string Terms,string body)
{
 try
  {

 MailMessage MyMessage = new System.Web.Mail.MailMessage();
 MyMessage.From = FromAddress.ToString();
 MyMessage.To = ToAddress.ToString();
 MyMessage.Bcc=BccAddress.ToString();
 MyMessage.Cc=CcAddress.ToString();
 MyMessage.Subject = Subject.ToString();
 MyMessage.Body =body.ToString();

 System.Web.Mail.SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"].ToString();
 //SMTP Server IP
 
 MailAttachment objMailAttach=new MailAttachment(Attachment);
 MyMessage.Attachments.Add(objMailAttach);

 if(Terms != "")
 {
 MailAttachment objMailAttach1=new MailAttachment(Terms);
 MyMessage.Attachments.Add(objMailAttach1);
 }

 MyMessage.BodyFormat = MailFormat.Text ;
 MyMessage.Fields.Add("
http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
 MyMessage.Fields.Add("
http://schemas.microsoft.com/cdo/configuration/sendusername",ConfigurationSettings.AppSettings["UserNam e"].ToString() ); //set your username here

MyMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", ConfigurationSettings.AppSettings["Password"].ToString() );

 System.Web.Mail.SmtpMail.Send(MyMessage);

 return true;

 }

 catch(Exception ex)
 {
  throw new Exception(ex.Message, ex);
 }

}

 

No comments:

Post a Comment