1

When using the code from this well read post

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential("my email", "my password")
};

I constantly get a System.Security.SecurityException: Request for the permission of type 'System.Net.Mail.SmtpPermission.

Does this code have to be used in some special hosting environment or am I missing somthing obvious?

Thanks!

Community
  • 1
  • 1
Cotten
  • 8,787
  • 17
  • 61
  • 98
  • No, you are probably on a shared host that disables sending emails via SMTP (i.e. you are in medium trust). This is a CAS problem. – vcsjones Jun 05 '12 at 17:37
  • Ok, yes, I was a bit too quick to get frustrated about this. Fails on dev server (cassini?) but on iis it works fine. – Cotten Jun 06 '12 at 11:00

1 Answers1

0

Sending email depends on how the SMTP server is configured.

According to gmail confiruged You need to remove this line of code

UseDefaultCredentials = false;

just comment this line and your message will be send.

 var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            // do not use this command
           // UseDefaultCredentials = false,
            Credentials = new NetworkCredential("username", fromPassword)
        };

Microsoft suggest not to use defaultcredentials when possible. See this link for clarification.

Md Kamruzzaman Sarker
  • 2,387
  • 3
  • 22
  • 38