Problems sending e-mail in web app

前端 未结 3 1670
悲哀的现实
悲哀的现实 2021-01-28 20:27

I have been trying for 2 days to get my ASP.NET webforms application to send an e-mail.

I have tried this using both outlook and gmail. I got the smtp information for bo

3条回答
  •  执念已碎
    2021-01-28 21:02

    This code should work fine for you

    protected void SendEmail()
    {
        string EmailAddress = "myemail@gmail.com";
        MailMessage mailMessage = new MailMessage(EmailAddress, EmailAddress);
        mailMessage.Subject = "This is a test email";
        mailMessage.Body = "This is a test email. Please reply if you receive it.";
    
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.EnableSsl = true;
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.Port = 587;
    
        smtpClient.Credentials = new System.Net.NetworkCredential()
        {
            UserName = EmailAddress,
            Password = "password"
        };
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Send(mailMessage);
    }
    

    You'll need to set the delivery mode otherwise gmail will return an error

    EDIT:

    Throwing an 'using' around 'MailMessage' might also be a smart thing to do

提交回复
热议问题