如何使用附件发送电子邮件从服务器路径asp.net C# [英] how to send email with attachment from server path in asp.net c#

查看:328
本文介绍了如何使用附件发送电子邮件从服务器路径asp.net C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要与我的asp.net的电子邮件附加文件。文件上传在Server.path。但我不知道怎么跟我的电子邮件添加此请指导我
我的code

I need to attach files with my email in asp.net. the files are uploaded in the Server.path. but I don't know how to add this with my email please guide me My code

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);
}

这code工作没有依附非常精细,回合依恋我得到这个错误:
发送邮件失败。

this code working very fine without attachment, bout with attachment i get this error: Failure sending mail.

推荐答案

您不必打开文件。

foreach (FileInfo file in dir.GetFiles("*.*"))
{
   if (file.Exists) 
   {
      mailMessage.Attachments.Add(new Attachment(file.FullName));
   }
}

这篇关于如何使用附件发送电子邮件从服务器路径asp.net C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆