Send Mail with Attachment using MVC
Introduction:
In this
section, I am going to explain how to
send mail with attachment using MVC. Here I created View to get data like receiver mail and
attached file. By using SMTP server it will generate mail with attachment.
Model:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace WebApplication2.Models
- {
- public class MailDetailsMod
- {
- public string MailTo { get; set; }
- public HttpPostedFileBase MailAttachment { get; set; }
- }
- }
View:
@model WebApplication2.Models.MailDetailsMod
@{
ViewBag.Title = "Send Mail With Attachment using MVC";
}
<center>
<h2>Send Mail
with Attachment</h2>
@using
(Html.BeginForm("SendMail", "Mail", FormMethod.Post, new {
enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>Mail To:</td>
<td>@Html.TextBoxFor(m
=> m.MailTo)</td>
</tr>
<tr>
<td>Attach
your file:</td>
<td>@Html.TextBoxFor(m
=> m.MailAttachment, new { type =
"file" })</td>
</tr>
</table>
<br />
<b><input type="submit" value="Click here to send mail" /><br /></b>
<h3> @ViewBag.SuccessMessage</h3>
}
</center>
Controller:
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Web.Mvc;
using WebApplication2.Models;
namespace WebApplication2.Controllers
{
public class MailController : Controller
{
// GET: Mail
public ActionResult SendMail()
{
MailDetailsMod myMod = new MailDetailsMod();
return View(myMod);
}
[HttpPost]
public ActionResult SendMail(MailDetailsMod myMod)
{
string Sendermail = "sender mail id";
using (MailMessage mm = new MailMessage(Sendermail, myMod.MailTo))
{
mm.Subject = "Mail Coding with Email Attachment";
mm.Body = "Hi, This is naveen from dotnet builders you can find
attachment in this mail.";
if (myMod.MailAttachment.ContentLength > 0)
{
string fileName = Path.GetFileName(myMod.MailAttachment.FileName);
mm.Attachments.Add(new Attachment(myMod.MailAttachment.InputStream, fileName));
}
mm.IsBodyHtml = false;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("your mail id", "your password");
smtp.UseDefaultCredentials
= true;
smtp.Credentials =
NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
ViewBag.SuccessMessage = "Email sent successfully !!!";
}
}
return View();
}
}
}
Screenshots:
Conclusion:
Congrats, You have successfully mailed with attachment using MVC. Keep in touch I will cover some new techniques in my next post.
If you are looking for the ultimate learning recourse for .NET developers then Dotnetmastery.com is here to provide you best online E-courses to learn the .Net and more courses online at best prices.
ReplyDeletelearn .net core MVC