简体   繁体   中英

How to attach a file to an email in c#

Hi I believe I am pretty close to figuring out what is wrong with my code, but was hoping someone could help me out or point me in the right direction. I am able to run my program and on the page where the user is going to be uploading a file it gives me the option to choose a file. But when I press submit other information gets sent to me but the file never comes. I think this is because I am having trouble figuring out where to temporarily save the file when it send to my email. Here is my code at the moment:

Also what this code is for is a comment / request page on my website where the user can comment and also add a screen shot.

private string SendMessage(string strTo, string strFrom, string strSubject, string    strMessage, string strAttachment, string strBCC)
{
    try
    {
        MailMessage mailMsg;
        string strEmail = "";
        string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
        string[] arrEmailAddress = strTo.Split(';');
        for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
        {
            strEmail = "";
            if (arrEmailAddress[intCtr].ToString().Trim() != "")
            {
                strEmail = arrEmailAddress[intCtr].ToString().Trim();
                mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
                mailMsg.IsBodyHtml = true;
                if (!strBCC.Trim().Equals(string.Empty))
                    mailMsg.Bcc.Add(strBCC);

                SmtpClient smtpClient = new SmtpClient(strSmtpClient);
                smtpClient.UseDefaultCredentials = true;
                smtpClient.Port = 25;

                smtpClient.Send(mailMsg);
                mailMsg.Dispose();
            }
        }
        return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
    }
    catch (Exception objEx)
    {
        return objEx.Message.ToString();
    }

    string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
    string strFileName1 = string.Empty;
    if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
    {
        string strUploadFileName1 = File1.PostedFile.FileName;
        strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
        strFileName1 = strFileName1.Replace("'", "");
        string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
        File1.PostedFile.SaveAs(strSaveLocation);
        txtComments.Text = "The file has been uploaded";
    }

My question is where am I going wrong where in this code do I put where I want the file to be saved.

The below part of the code is what I am using to format the email when it is sent. And pick what will be sent in the email.

protected void Submit_Click1(object sender, EventArgs e)
{
    try
    {
        string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
        string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
                     "Module Name: " + ddlModule.SelectedValue + "<br/>" +
                     "Page Name: " + ddlPage.SelectedValue + "<br/>" +
                     "Description: " + txtComments.Text.Trim() + "<br/>" +
                      File1.f + "<br/>" +
                      "Email is" + " " + txtemail.Text.Trim() + "<br/>" +
                      "The request was sent at" + dandt;  

        SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
            ConfigurationManager.AppSettings["EmailAddrFrom"],
            txtBugName.Text.Trim(),
            strMessage, "", "");
    }
    catch 
    {
    }
}

For some reason now nothing is sending in my emails when I press submit. Also I was trying to figure out how to put in the email the time and date the email was sent. Even though obviously my email will have this information, incase the email is delayed for some reason I would like to have the time and date the user pressed the submit button. Where is says File.F in this part of the code this is where i was trying to figure out how to get the file attachment to go to the email, but I'm not sure what syntax should go there in the code.

It looks like you are trying to attach some file from the user's computer to the email you are sending. If that is the case, you need to upload your file first before you call SendMessage.

In your Submit_Click the first thing you need to do is the code the uploads the file somewhere. Also, remove that File1.f from strMessage which is where I suspect is causing your message to null out on you.

After you upload your file, pass strSavedLocation , which is the file location you saved the file, to your SendMessage() method.

In your SendMessage method you can attach the file with the following code where you are buliding your MailMessage . strAttachment is the path name to your uploaded file:

var attachment = new Attachment(strAttachment);
// Add time stamp information for the file.
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(strAttachment);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(strAttachment);
disposition.ReadDate = System.IO.File.GetLastAccessTime(strAttachment);
mailMsg.Attachments.Add(attachment);

It looks to me like you have the major parts here minus the handy, System.Net.Mail.Attachment.

If I were doing this, I'd move the file upload handling code into the Submit_Click handler, and then just add the Mail.Attachment code.

    private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
    {
        try
        {
            System.Net.Mail.MailMessage mailMsg;
            string strEmail = "";
            string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
            string[] arrEmailAddress = strTo.Split(';');
            for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
            {
                strEmail = "";
                if (arrEmailAddress[intCtr].ToString().Trim() != "")
                {
                    strEmail = arrEmailAddress[intCtr].ToString().Trim();
                    mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
                    mailMsg.IsBodyHtml = true;
                    if (!strBCC.Trim().Equals(string.Empty))
                        mailMsg.Bcc.Add(strBCC);

                    /*** Added mail attachment handling ***/    
                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(strAttachment);
                    mailMsg.Attachments.Add(attachment);

                    SmtpClient smtpClient = new SmtpClient(strSmtpClient);
                    smtpClient.UseDefaultCredentials = true;
                    smtpClient.Port = 25;

                    smtpClient.Send(mailMsg);
                    mailMsg.Dispose();
                }
            }
            return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
        }
        catch (Exception objEx)
        {
            return objEx.Message.ToString();
        }
    }

    protected void Submit_Click1(object sender, EventArgs e)
    {
        try
        {
            /*** Moved from SendMessage function ****/
            string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            string strFileName1 = string.Empty;
            if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
            {
                string strUploadFileName1 = File1.PostedFile.FileName;
                strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
                strFileName1 = strFileName1.Replace("'", "");
                string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
                File1.PostedFile.SaveAs(strSaveLocation);
                txtComments.Text = "The file has been uploaded";
            }

            string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
                         "Module Name: " + ddlModule.SelectedValue + "<br/>" +
                         "Page Name: " + ddlPage.SelectedValue + "<br/>" +
                         "Description: " + txtComments.Text.Trim() + "<br/>" +
                          strSaveLocation + "<br/>" +
                          "Email is" + " " + txtemail.Text.Trim() + "<br/>" +
                          "The request was sent at" + dandt;


            SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
                ConfigurationManager.AppSettings["EmailAddrFrom"],
                txtBugName.Text.Trim(),
                strMessage, strSaveLocation, "");
        }
        catch
        {
        }
    }

As for the note about using StringBuilder, I agree, and I would use it like this:

System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat("Bug Name: {0}<br/>", txtBugName.Text.Trim());
sb.AppendFormat("Module Name: {0}<br/>", ddlModule.SelectedValue);       

Edited To Add: Also, see Brad's answer above about using ContentDisposition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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