Search This Blog

Sunday, April 29, 2012

Send Mail using WebService



Requisites

  1. using System.Net.Mail;
  2. WebMethod in Remote Server
  3. Host the Remote Application in Server
  4. Client Application to send mail using Remote web-service

Using the code

 
[WebMethod]
public bool SendMail(string
fromAddress, string toAddress, string subject, string body)
 {
 try
 {
 MailMessage msg = new MailMessage();
 msg.From = new MailAddress(fromAddress);
 msg.To.Add(new MailAddress(toAddress));
 msg.Subject = subject;
 msg.Body = body;
 msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(msg);
return true;
}
catch(Exception exp)
{
return false;
}
}
**Note the server IP-Address and virtual directory name

Next step is to Create Local Application
 <form id="form1" runat="server">
   <div><br />        To :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
 <asp:TextBox ID="TextBox1" runat="server" Width="279px"></asp:TextBox> 
   <br />         Subject: <asp:TextBox ID="TextBox2" runat="server" Width="388px"></asp:TextBox> 
     <br />   
    Body :&nbsp;&nbsp;  <asp:TextBox ID="TextBox3" runat="server" Height="185px" TextMode="MultiLine"  Width="466px"></asp:TextBox>  
  <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:Button ID="btnSendMail" runat="server" onclick="btnSendMail_Click"         Text="sendMail" />    
   </div>                                                                        
 </form>
Design your form as per your requirement       
Next Step is to create a web-reference in your local application
Right click on Solution Explorer and select add web-reference, which will show the following screen.    
Add Server-IP followed by virtual directory name and yourfilename.asmx file name as mentioned below.
  
Then Click on Add Reference button.
protected void btnSendMail_Click(object sender, EventArgs e)                                 
 {
WebReference.WebService2 obj = new WebReference.WebService2();      
 obj.SendMail("sanjaya@scalable-systems.com",TextBox1.Text, TextBox2.Text ,TextBox3.Text);      
 }                                                                                               

No comments:

Post a Comment