chris
chris

Reputation: 1

Error CS1729: 'Attachment' does not contain a constructor that takes 2 arguments

I am trying to send mail with attachment through smtp protocol, so I found this tutorial in http://csharpdotnetfreak.blogspot.com/2009/10/send-email-with-attachment-in-aspnet.html. And tried the following simple coding, the object got created correctly for attachment but it tell me the error that does not take 2 arguments.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class composemail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendMail()
{
    MailMessage mail = new MailMessage();
    mail.To.Add(YourEmail.Text);
    mail.From = new MailAddress(YourName.Text);
    mail.Subject = YourSubject.Text;
    mail.Body = Comments.Text;
    mail.IsBodyHtml = true;
    if (FileUpload1.HasFile)
    {
        mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    SendMail();
}
}

Upvotes: 0

Views: 1665

Answers (1)

Sani Huttunen
Sani Huttunen

Reputation: 24385

As M4N mentioned you cannot have code directly in the class. You need to encapsulate it in a method:

using System.IO;
using System.Net.Mail;

namespace AttachmentTest
{
  class Program
  {
    static void Main(string[] args)
    {
      var mail = new MailMessage();
      var fs = new FileStream("somepath", FileMode.Open);
      var att = new Attachment(fs, "");
      mail.Attachments.Add(att);
    }
  }
}

Upvotes: 1

Related Questions