Hi darshanbihani,
In order to send email with attachment you need to make use of FormData.
Attach the control values to the FormData using append method and access inside the Web Service.
Sending Email using Web Service
Using the above article i have modified the code for attaching file using File Upload control and other controls value to Form Data.
Mail Server Settings in Web.Config file
Following are the Mail Server settings in the Web.Config file.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sender@gmail.com">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="sender@gmail.com"
password="SenderGmailPassword"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
HTML
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>To:</td>
<td><asp:TextBox ID="txtTo" runat="server" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:TextBox ID="txtSubject" runat="server" /></td>
</tr>
<tr>
<td valign="top">Body:</td>
<td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Height="150" Width="200" /></td>
</tr>
<tr>
<td>Attachment:</td>
<td><asp:FileUpload ID="fuUpload" runat="server" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSend" Text="Send" runat="server" /></td>
</tr>
</table>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=btnSend]").click(function () {
var toEmail = $.trim($("[id*=txtTo]").val());
var subject = $.trim($("[id*=txtSubject]").val());
var body = $.trim($("[id*=txtBody]").val());
var formData = new FormData();
formData.append("Email", toEmail);
formData.append("Subject", subject);
formData.append("Body", body);
formData.append("File", $("[id*=fuUpload]")[0].files[0]);
$.ajax({
type: 'POST',
url: "Service.asmx/SendEmail",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (r) {
},
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
});
return false;
});
});
</script>
Web Service
C#
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for Service
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string SendEmail()
{
// Reading Form controls value.
string toEmail = HttpContext.Current.Request.Form["Email"];
string subject = HttpContext.Current.Request.Form["Subject"];
string body = HttpContext.Current.Request.Form["Body"];
HttpPostedFile fuAttachment = HttpContext.Current.Request.Files["File"];
// Reading mailSettings from Web.Config.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(smtpSection.From, toEmail))
{
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = false;
// Attaching the File to MailMessage object.
if (fuAttachment.ContentLength > 0)
{
mm.Attachments.Add(new Attachment(fuAttachment.InputStream, Path.GetFileName(fuAttachment.FileName)));
}
// Creating SmtpClient object.
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = smtpSection.Network.Host;
smtp.EnableSsl = smtpSection.Network.EnableSsl;
NetworkCredential networkCred = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials;
smtp.Credentials = networkCred;
smtp.Port = smtpSection.Network.Port;
// Sending Email.
smtp.Send(mm);
}
}
return "Email sent.";
}
}
VB.Net
Imports System.Configuration
Imports System.IO
Imports System.Net
Imports System.Net.Configuration
Imports System.Net.Mail
Imports System.Web
Imports System.Web.Services
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits WebService
<WebMethod>
Public Function SendEmail() As String
' Reading Form controls value.
Dim toEmail As String = HttpContext.Current.Request.Form("Email")
Dim subject As String = HttpContext.Current.Request.Form("Subject")
Dim body As String = HttpContext.Current.Request.Form("Body")
Dim fuAttachment As HttpPostedFile = HttpContext.Current.Request.Files("File")
' Reading mailSettings from Web.Config.
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Using mm As MailMessage = New MailMessage(smtpSection.From, toEmail)
mm.Subject = subject
mm.Body = body
mm.IsBodyHtml = False
' Attaching the File to MailMessage object.
If fuAttachment.ContentLength > 0 Then
mm.Attachments.Add(New Attachment(fuAttachment.InputStream, Path.GetFileName(fuAttachment.FileName)))
End If
' Creating SmtpClient object.
Using smtp As SmtpClient = New SmtpClient()
smtp.Host = smtpSection.Network.Host
smtp.EnableSsl = smtpSection.Network.EnableSsl
Dim networkCred As NetworkCredential = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
smtp.Credentials = networkCred
smtp.Port = smtpSection.Network.Port
' Sending Email.
smtp.Send(mm)
End Using
End Using
Return "Email sent."
End Function
End Class
Screenshots
The Form
The Recieved Email