Albert Cortada
Albert Cortada

Reputation: 747

Send email from webservice

I have a method to send mails from c#:

public static void SendEmailWebService(string asunto, string body, string to)
{
    try
    { // takes config from web.config
        MailMessage mm = new MailMessage
        {
            From = new MailAddress(@"[email protected]", @"Notificacion"),
            To = { new MailAddress(to) },
            Subject = asunto,
            IsBodyHtml = true,
            Body = body,
            HeadersEncoding = System.Text.Encoding.UTF8,
            SubjectEncoding = System.Text.Encoding.UTF8,
            BodyEncoding = System.Text.Encoding.UTF8
        };
        Smtp.Send(mm);
    }
    catch (Exception ex)
    {
        // Error
    }
}

If i call this method normaly, it works, but if i call it from a webservice then it fails.

In the cathc, the exception is:

This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server.

I don't see why it's not worikng when I call it from the webservice.

Upvotes: 0

Views: 855

Answers (1)

Steve
Steve

Reputation: 3703

The error message is saying your mail server requires authentication. While there are many ways to achieve this, you can create a new NetworkCredential object and supply that to your mailmessage named parameters:

public static void SendEmailWebService(string asunto, string body, string to)
{
    try
    { // takes config from web.config
        MailMessage mm = new MailMessage
        {
            From = new MailAddress(@"[email protected]", @"Notificacion"),
            To = { new MailAddress(to) },
            Subject = asunto,
            IsBodyHtml = true,
            Body = body,
            HeadersEncoding = System.Text.Encoding.UTF8,
            SubjectEncoding = System.Text.Encoding.UTF8,
            BodyEncoding = System.Text.Encoding.UTF8,
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential("username", "password")
        };
        Smtp.Send(mm);
    }
    catch (Exception ex)
    {
        // Error
    }
}

If you don't want to add the NetworkCredential to your source code you can also configure it from the web.config file

<system.net>
  <mailSettings>
    <smtp>
      <network host="" port="" userName="" password=""/>
    </smtp>
  </mailSettings>
</system.net> 

Upvotes: 3

Related Questions