cannot send fileupload.postedfile.inputstream as an attachment - ERROR: cannot convert system.io.stream to string

Refresh

February 2019

Views

26 time

1

I need to send a pdf as an attachment. I am using a html template as mailbody. My problem is the error displayed while trying to send the attachment as follows.

email.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream), pdffilename);

The FileUpload1.PostedFile.InputStream is the error code.

My full code is displayed below:

private void send_job_notification(string name, string app_email, string job_id, string job_title, string experience,string pdffilename)
    {
        string to = "[email protected]";
        SmtpClient smtp_server = new SmtpClient();
        MailMessage email = new MailMessage("[email protected]", to);
        smtp_server.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp_server.UseDefaultCredentials = false;
        smtp_server.Credentials = new System.Net.NetworkCredential("[email protected]", "PASSWORD");
        smtp_server.Port = 25;
        smtp_server.EnableSsl = false;
        smtp_server.Host = "zzz.bbb.com";
        email.From = new MailAddress("[email protected]");
        email.To.Add(to);
        email.Subject = "New Job request submitted for company";
        email.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream), pdffilename);
        email.IsBodyHtml = true;
        string FilePath = Server.MapPath("~/emailnewtemplate.html");
        StreamReader str = new StreamReader(FilePath);
        string MailText = str.ReadToEnd();
        str.Close();
        string line1 = "<h4>Dear Management</h4>";
        string line2 = "<h4>A new job request has been receieved. The applicant details are as follows</h4>";
        string table_open = "<table class='table table-responsive-sm'>";
        string row_1 = "<tr><td>Name : </td><td> " + name + " </td></tr>";
        string row_2 = "<tr><td>Email : </td><td> " + app_email + " </td></tr>";
        string row_3 = "<tr><td>Job ID : </td><td> " + job_id + " </td></tr>";
        string row_4 = "<tr><td>Job Title : </td><td> " + job_title + " </td></tr>";
        string row_5 = "<tr><td>Experience : </td><td> " + experience + " </td></tr>";
        string table_close = "</table>";
        string line3 = table_open + row_1 + row_2 + row_3 + row_4 + row_5 + table_close;
        string htmlbody = line1 + line2 + line3;
        MailText = MailText.Replace("[#####HERE#####]", htmlbody);
        email.Body = MailText;
        smtp_server.Send(email);
   }

1 answers

0

I think a wrongly placed bracket is your problem, It looks like you tried to use the constructor Attachment(Stream, String) of the Attachment class but you supplied only the stream. the constructor of Attachment class that accepts only one parameter is expecting a string that's what the error message says

correct it as :

email.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, pdffilename));