Question

I wish to send emails with multiple Resumes. Each student has a profile which has their Resumes attached (some students have more than one) and these are stored in the database. Users search for students that meet certain criteria and email the students Resumes to potential employers.

Database:

cvID - int
UserName - varchar(50)
FileName - varchar(50)
FileType - nvarchar(50)
Data - varbinary(MAX)

When a search is conducted the appropriate students display in the results each with a DropDown box of their available Resumes. The user selects the Resume from the DropDown box they wish to attach to the email, clicks 'Attach', and that FileName is then added to a ListBox in the email area.

Once the user has selected all Resumes they wish to attach, they then fill in the remaining email fields... To, From, Subject, Message etc. When the user clicks 'Send' I need the code to attach the files listed inside the ListBox from the database and send the email.

ASPX.CS Page
Using System.Net.Mail

protected void emlSend_Click(object sender, EventArgs e)
{
    MailMessage email = new MailMessage();

    email.From = new MailAddress(txtFrom.Text);
    email.To.Add(txtTo.Text);
    email.Subject = txtSub.Text;
    email.Body = txtMsg.Text;

    //Loop through lstFiles to get all values
    foreach (ListItem item in lstFiles.Items)
    {
        if (item.Selected)
        {
            //Save value to string
            string lstItem = item.Text;
            string lstValue = item.Value;

            //Connect to Server
            string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    //Use value in Select statement
                    cmd.CommandText = "SELECT FileName, FileType, Data from CVData where cvID = '" + lstValue + "'";
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        //Get CV Data
                        sdr.Read();
                        bytes = (byte[])sdr["Data"];
                        fileName = sdr["FileName"].ToString();

                        //Attach Data as Email Attachment
                        email.Attachments.Add(... //This is where I am now stuck

                    }
                    con.Close();
                }
            }
        }
}

Using the below...

email.Attachments.Add(new Attachment(new MemoryStream(bytes, fileName)));

gives me this error:

Compiler Error Message: CS1502: The best overloaded method match for 'System.IO.MemoryStream.MemoryStream(byte[], bool)' has some invalid arguments

If I'm attempting this the wrong way please let me know. This is my first time trying to do something like this so any help would be much appreciated!!

Was it helpful?

Solution 2

protected void emlSend_Click(object sender, EventArgs e)
{

    byte[] bytes;
    string fileName;

    MailMessage email = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("attgmail");

    email.From = new MailAddress(txtFrom.Text);
    email.To.Add(txtTo.Text);
    email.Subject = txtSub.Text;
    email.Body = txtMsg.Text;

    //Loop through lstFiles to get all values
    foreach (ListItem item in lstFiles.Items)
    {
        if (item.Selected)
        {
            //Save value to string
            string lstItem = item.Text;
            string lstValue = item.Value;

            //Connect to Server
            string constr = ConfigurationManager.ConnectionStrings["fishbowlConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    //Use value in Select statement
                    cmd.CommandText = "SELECT FileName, FileType, Data from CVData where cvID = '" + lstValue + "'";
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        //Get CV Data
                        sdr.Read();
                        bytes = (byte[])sdr["Data"];
                        fileName = sdr["FileName"].ToString();

                        //This works if files are stored in folder instead of the below code
                        //Attachment resume = new Attachment(Server.MapPath(VirtualPathUtility.ToAbsolute("~/images/cv/" + fileName)));

                        //Attach Data as Email Attachment
                        MemoryStream pdf = new MemoryStream(bytes);
                        Attachment data = new Attachment(pdf, fileName);
                        email.Attachments.Add(data);
                    }
                    con.Close();
                }
            }
        }
    }

    //send the message
    SmtpClient smtp = new SmtpClient();
    smtp.Send(email);

    lblEmail.Text = "Email was sent Successfully";
}

OTHER TIPS

You need to use System.Net.Mail namespace. The System.Web.Mail.MailMessage is obsolete.

and here is how you add attachments to the MailMessage.

// assumption is that the dropdown values contain a key to the file
// contents (resume) in the DB and the contents are retrieved as a 
// byte array.

if (lstFiles != null)
{
 foreach (var fileName in lstFiles)
 {
  int cvId = 42; // can come from dropdown etc. basically a key to the file.
  byte[] resumeBytes = GetResumeFromDatabaseAsBytes(cvId);
  email.Attachments.Add(new Attachment(new MemoryStream(resumeBytes, fileName)));
 }
}

public static byte[] GetResumeFromDatabaseAsBytes(int cvID)
{
 var connectionString = "YOUR_CONNECTION_STRING";

 using (var sqlConnection = new SqlConnection(connectionString))
 {
     using (var sqlCommand = new SqlCommand("SELECT TOP 1 FileName, FileType, Data From  RESUME_TABLE_NAME Where cvID = " + cvID, sqlConnection))
    {
        using (var reader = sqlCommand.ExecuteReader())
        {
            if (reader.Read())
            {
                // e.g. John_Doe.docx
                string fileName = reader["FileName"].ToString() + "." + reader["FileType"].ToString();
                byte[] cvData = (byte[])reader["Data"];

                //return cvData;
            }
        }
    }
 }
}

the above is just a sample to get the resume contents. you can get all the resumes in 1 call by passing the right parameters. let us know the data access method you're using.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top