我正在开发一个ASP.NET MVC项目。在我的项目中,我需要发送带附件的电子邮件。但是当我发送电子邮件时,电子邮件已成功发送,但不包括附件。
这是我的发送电子邮件方式
public bool Send(string email, string subject, string body, HttpPostedFileBase fileUploader, bool html = true)
{
try
{
string from = AppEmail; //example:- sourabh9303@gmail.com
using (MailMessage mail = new MailMessage(from, email))
{
mail.Subject = subject;
mail.Body = body;
if (fileUploader != null && fileUploader.ContentLength>0)
{
string fileName = Path.GetFileName(fileUploader.FileName);
mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
}
mail.IsBodyHtml = html;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential(from, EmailPassword);
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
return true;
}
}
catch
{
return false;
}
}
那么为什么不包括附件?如何发送带附件的电子邮件?
答案 0 :(得分:1)
<强>命名空间强> 您需要导入以下命名空间
using System.IO;
using System.Net;
using System.Net.Mail;
<强>模型强> 以下是名为EmailModel的Model类,具有以下属性。
public class EmailModel
{
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public HttpPostedFileBase Attachment { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
<强>控制器强>
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(EmailModel model)
{
using (MailMessage mm = new MailMessage(model.Email, model.To))
{
mm.Subject = model.Subject;
mm.Body = model.Body;
if (model.Attachment.ContentLength > 0)
{
string fileName = Path.GetFileName(model.Attachment.FileName);
mm.Attachments.Add(new Attachment(model.Attachment.InputStream, fileName));
}
mm.IsBodyHtml = false;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(model.Email, model.Password);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
ViewBag.Message = "Email sent.";
}
}
return View();
}
}
查看强>
@model Send_Email_MVC.Models.EmailModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
table th, table td {
padding: 5px;
}
</style>
</head>
<body>
<div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 80px">
To:
</td>
<td>
@Html.TextBoxFor(model => model.To)
</td>
</tr>
<tr>
<td>
Subject:
</td>
<td>
@Html.TextBoxFor(model => model.Subject)
</td>
</tr>
<tr>
<td valign="top">
Body:
</td>
<td>
@Html.TextAreaFor(model => model.Body, new { rows = "3", cols = "20" })
</td>
</tr>
<tr>
<td>
File Attachment:
</td>
<td>
@Html.TextBoxFor(model => model.Attachment, new { type = "file" })
</td>
</tr>
<tr>
<td>
Gmail Email:
</td>
<td>
@Html.TextBoxFor(model => model.Email)
</td>
</tr>
<tr>
<td>
Gmail Password:
</td>
<td>
@Html.TextBoxFor(model => model.Password, new { type = "password" })
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Send"/>
</td>
</tr>
</table>
<br/>
<span style="color:green">@ViewBag.Message</span>
}
</div>
</body>
</html>
答案 1 :(得分:-1)
您可以使用此解决方案:
创建此类
public class Attachment
{
public string Path { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
}
然后创建此界面
public interface IFileAttachmentService
{
Attachments Save(HttpPostedFileBase file);
}
然后在这个类上实现接口
public class FileAttachmentService : IFileAttachmentService
{
private static readonly string _folder = "~/Attachments/";
public Attachments Save(HttpPostedFileBase file)
{
if (file == null)
return new Attachments();
var savePath = GenerateUniqueFileName(_folder + Path.GetFileName(file.FileName));
file.SaveAs(HttpContext.Current.Server.MapPath(savePath));
return new Attachments
{
ContentType = file.ContentType,
Name = Path.GetFileName(file.FileName),
Path = savePath
};
}
private string GenerateUniqueFileName(string basedOn)
{
if (string.IsNullOrWhiteSpace(basedOn))
throw new ArgumentNullException("basedOn");
return (Path.GetDirectoryName(basedOn)
+ "\\"
+ Path.GetFileNameWithoutExtension(basedOn)
+ "."
+ Path.GetRandomFileName()
+ Path.GetExtension(basedOn))
.Replace('\\', '/');
}
}
然后创建此方法
public static void SendEmail(string to, string toName, string subject, string body, string attachment)
{
var fromAddress = new MailAddress("Your Gemail Address", "Sender Project System Name");
var toAddress = new MailAddress(to, toName);
var att = new Attachment(HttpContext.Current.Server.MapPath(attachment));
const string fromPassword = "Your pass";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
message.Attachments.Add(att);
smtp.Send(message);
}
}
请小心将附件文件设置为正确的模式,如果您不需要使用附件文件发送重载此方法而不附加参数。