简体   繁体   English

如何从asp.net C#中的服务器路径发送带有附件的电子邮件

[英]how to send email with attachment from server path in asp.net c#

I need to attach files with my email in asp.net. 我需要在asp.net的电子邮件中附加文件。 the files are uploaded in the Server.path. 文件将上传到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);
}

this code working very fine without attachment, bout with attachment i get this error: Failure sending mail. 此代码在没有附件的情况下工作非常好,与附件回合我收到此错误:发送邮件失败。

You do not need to Open files. 您不需要打开文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM