简体   繁体   English

如何在C#中将文件附加到电子邮件

[英]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. 在这部分代码中,File.F表示的位置是我试图弄清楚如何将附件发送到电子邮件的地方,但是我不确定代码中应该使用哪种语法。

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. 在这种情况下,您需要先上载文件,然后再调用SendMessage.

In your Submit_Click the first thing you need to do is the code the uploads the file somewhere. Submit_Click ,您需要做的第一件事就是将文件上传到某处的代码。 Also, remove that File1.f from strMessage which is where I suspect is causing your message to null out on you. 另外,从strMessage删除该File1.f ,我怀疑这是导致您的消息消失的地方。

After you upload your file, pass strSavedLocation , which is the file location you saved the file, to your SendMessage() method. 上传文件后,将strSavedLocation (这是您保存文件的文件位置)传递到SendMessage()方法。

In your SendMessage method you can attach the file with the following code where you are buliding your MailMessage . 在您的SendMessage方法中,可以使用以下代码将文件附加到构建MailMessage strAttachment is the path name to your uploaded file: strAttachment是您上传的文件的路径名:

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. 在我看来,您这里的主要部分要减去方便的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. 如果这样做,则将文件上传处理代码移到Submit_Click处理程序中,然后仅添加Mail.Attachment代码。

    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: 至于关于使用StringBuilder的说明,我同意,我会这样使用它:

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. 编辑添加:另外,请参见上面关于使用ContentDisposition的Brad的回答。

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

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