Unable to send E-mail with Attachment

2019-09-21 16:33发布

问题:

My issue is this that I am trying to make use of email sending task at my website for the admin individual.

When he selects the email ids from the available data, adds an attachment and sends the email, it was never received by user. However, if he is using simple mailing ie. without any attachment, user receives it.

Can you help please ?

My coding is given below :-

public partial class SahibAdmin_emailNewsletter : System.Web.UI.Page
{
  // ... 

  private void SendNewsletter(string emailId)
  {
        System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();
        message.To = emailId;
        message.From = "info@sahibimports.com";
        message.Subject = "Please See: Newsletter from Sahib imports";
        message.BodyFormat = System.Web.Mail.MailFormat.Text;
        message.Body = txtBody.Text.ToString();
        if (msgUpload.HasFile)
        {
              //string strFileName = msgUpload.FileName;
              //msgUpload.PostedFile.SaveAs(Server.MapPath(strFileName));
              //System.Web.Mail.MailAttachment attach =
              //  new System.Web.Mail.MailAttachment(Server.MapPath(strFileName));
              //message.Attachments.Add(attach);

              message.Attachments.Add(new Attachment(
                 FileUpload.PostedFile.InputStream, FileUpload.FileName));

        }
        System.Web.Mail.SmtpMail.Send(message);
        Response.Flush();

  }

回答1:

According to http://msdn.microsoft.com/en-us/library/6sdktyws.aspx your Attachment constructor is trying to set the ContentType with the second parameter but you're passing in a filename, are you sure that is correct?

You should probably change that part to something like:

ContentType contentType = // create suitable type here based on your file format
Attachment attachment = new Attachment(
    FileUpload.PostedFile.InputStream,
    contentType
);
attachment.ContentDisposition.FileName = FileUpload.FileName;
message.Attachments.Add(attachment);


回答2:

You are trying to use System.Net.Mail.Attachment with System.Web.Mail.MailMessage.

These API`s are incompatible with each other. System.Web.Mail.MailMessage only supports System.Web.Mail.MailAttachment, not System.Net.Mail.Attachment.