Search code examples
c#emailemail-attachments

Unable to send E-mail with Attachment


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();

  }

Solution

  • 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);