Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Send Email

Tags:

email

asp.net

I am trying to send a email when user clicks submit in a contact us page but for some reason its not working, what am I doing wrong? (PS email & password was omited from this code snippet but included in actual solution.

Thanks

Code in web.config:

<system.net>
<mailSettings>
  <smtp from="[email protected]">
    <network host="smtp.gmail.com"
             userName="" //my email
             password="" //password deleted for privacy reasons
             defaultCredentials="false"
             port="456"
             enableSsl="true" />
  </smtp>
</mailSettings>

code in asp.net contact form:

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add(new MailAddress("[email protected]"));
        mail.Subject = "Test";
        mail.Body = "Message was sent from" + txtName.text + txtComment.text;
        SmtpClient smtp = new SmtpClient();
        smtp.SendAsync(mail, null);
    }
like image 617
rikket Avatar asked Dec 24 '12 17:12

rikket


2 Answers

Gmails uses port 465, not 456 for SSL SMTP. From here:

Outgoing Mail (SMTP) Server - requires TLS1 or SSL: smtp.gmail.com

Use Authentication: Yes

Port for TLS/STARTTLS: 587

Port for SSL: 465

like image 62
keyboardP Avatar answered Sep 28 '22 04:09

keyboardP


The "other" possible reason:

  • Does your code "work" when developing locally, but stops working when you "publish"/ftp/copy, etc. your files to your web host?

  • If Yes: check your host's trust settings for ASP.Net. If it's medium trust (which is likely in shared hosting), then note that you cannot use any port other than port 25 for SMTP in medium trust.

It works locally (dev) because in local dev/VS environment, ASP.Net runs in full trust.

REF (MSDN Blogs): SMTP Problems when ASP.Net is not running in full-trust

like image 28
EdSF Avatar answered Sep 28 '22 04:09

EdSF