Sending mail is an easy task, using web-service has added some additional flavor to it.What i mean to say is if you know how to use a web-service it is not confined to web application only rather a windows form, applications like c++,java,vb programs can also consume the same web-service to send mail.
Introduction
In this article I am going to show how to send mail using
web service.
Requisites
- using System.Net.Mail;
- WebMethod in Remote Server
- Host the Remote Application in Server
- 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 :
<asp:TextBox ID="TextBox1" runat="server" Width="279px"></asp:TextBox>
<br /> Subject: <asp:TextBox ID="TextBox2" runat="server" Width="388px"></asp:TextBox>
<br />
Body : <asp:TextBox ID="TextBox3" runat="server" Height="185px" TextMode="MultiLine" Width="466px"></asp:TextBox>
<br /> <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);
}
In the above code the from address i have used as static value i.e sanjaya@scalable-systems.com. You can make it to dynamic as per your requirement.
Conclusion
From the above discussion it is very much clear how a user can easily send email from his local application using remote web-service.