如何在asp.net c#中从服务器路径发送带有附件的邮件
本文关键字:路径 服务器 asp net | 更新日期: 2023-09-27 18:10:59
我需要在asp.net中附加我的电子邮件文件。文件上传到Server.path。但是我不知道如何在我的邮件中添加这个,请指导我我的代码
public static void SendEmail_With_Attachment(String ToEmail, String Subj, string Message, string sourcePath)
{
//reading sender email credential from web.config file
HostAdd = ConfigurationManager.AppSettings["Host"].ToString();
FromEmailid = ConfigurationManager.AppSettings["FromMail"].ToString();
Pass = ConfigurationManager.AppSettings["Password"].ToString();
//creating the object of mailmessage
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = new MailAddress(FromEmailid);
mailMessage.Subject = Subj;
mailMessage.Body = Message;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(ToEmail));
FileStream fStream;
DirectoryInfo dir = new DirectoryInfo(sourcePath);
foreach (FileInfo files in dir.GetFiles("*.*"))
{
fStream = File.OpenRead(sourcePath + "''" + files.Name);
mailMessage.Attachments.Add(new System.Net.Mail.Attachment(fStream, files.Name));
fStream.Close();
}
SmtpClient smtp = new SmtpClient();
smtp.Host = HostAdd;
//network and security related credentia
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential();
NetworkCred.UserName = mailMessage.From.Address;
NetworkCred.Password = Pass;
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mailMessage);
}
这个代码工作很好没有附件,关于附件我得到这个错误:邮件发送失败
您不需要打开文件。
foreach (FileInfo file in dir.GetFiles("*.*"))
{
if (file.Exists)
{
mailMessage.Attachments.Add(new Attachment(file.FullName));
}
}