Using ASP.NET MailMessage class with MONO. Troubleshooting

There is an example how to use the MailMessage class in case you are using the ordinary ASP.NET hosting and the difference when you are running your website using MONO technology.

asp.net logo

The MailMessage Class provides properties and methods for constructing an e-mail message. But there are some troubles using it with MONO. See the examples how to avoid this.

The usual way to use MailMessage Class (we used .NET Framework 3.5 and C#)


using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SoftElegance.web
{
public partial class SEmail : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
lblError.InnerText = "";
}

protected void tbSubmit_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();

m.Subject = "subject";
m.To.Add(new System.Net.Mail.MailAddress(Properties.Settings.Default.RFQRecipient));


try
{
m.From = new System.Net.Mail.MailAddress(tbEmail.Text.Trim());
}
catch (Exception ex)
{
m.From = new System.Net.Mail.MailAddress(Properties.Settings.Default.RFQRecipient);
}
m.Body = "message";


try
{
if (fuAttach.HasFile)
m.Attachments.Add(new System.Net.Mail.Attachment(fuAttach.FileContent, fuAttach.FileName));


System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient(Properties.Settings.Default.SmtpServer);
s.UseDefaultCredentials = false;
s.Credentials = new System.Net.NetworkCredential(Properties.Settings.Default.SmtpUsername, Properties.Settings.Default.SmtpPassword);
s.Send(m);
}

catch (Exception ex)
{
lblError.InnerText = ex.Message;
}
}
}
}

But this code will not send the messages when your website works using MONO
You should use the following code:


using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SoftElegance.web
{
public partial class SEmail : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
lblError.InnerText = "";
}

protected void tbSubmit_Click(object sender, EventArgs e)
{
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage();

m.Subject = "subject";
m.To.Add(new System.Net.Mail.MailAddress(Properties.Settings.Default.RFQRecipient));
m.From = new System.Net.Mail.MailAddress(Properties.Settings.Default.SmtpUsername);
m.Body = "message";


try
{
if (fuAttach.HasFile)
m.Attachments.Add(new System.Net.Mail.Attachment(fuAttach.FileContent, fuAttach.FileName));


System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient(Properties.Settings.Default.SmtpServer);
s.UseDefaultCredentials = false;
s.Credentials = new System.Net.NetworkCredential(Properties.Settings.Default.SmtpUsername, Properties.Settings.Default.SmtpPassword);
s.Send(m);
}

catch (Exception ex)
{
lblError.InnerText = ex.Message;
}
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *