Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show.
Is it possible to do it?
NET and . NET Core come with built-in support for sending emails through the System. Net.Mail namespace. While it might seem like the easy choice, you will need an SMTP server for this to work.
Use the Gmail SMTP serverIf you connect using SSL or TLS, you can send mail to anyone inside or outside of your organization using smtp.gmail.com as your server. This option requires you to authenticate with your Gmail or Google Workspace account and passwords.
Be sure to use System.Net.Mail
, not the deprecated System.Web.Mail
. Doing SSL with System.Web.Mail
is a gross mess of hacky extensions.
using System.Net; using System.Net.Mail; var fromAddress = new MailAddress("[email protected]", "From Name"); var toAddress = new MailAddress("[email protected]", "To Name"); const string fromPassword = "fromPassword"; const string subject = "Subject"; const string body = "Body"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); }
Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting.
fromPassword
constant instead of your standard Gmail password.The above answer doesn't work. You have to set DeliveryMethod = SmtpDeliveryMethod.Network
or it will come back with a "client was not authenticated" error. Also it's always a good idea to put a timeout.
Revised code:
using System.Net.Mail; using System.Net; var fromAddress = new MailAddress("[email protected]", "From Name"); var toAddress = new MailAddress("[email protected]", "To Name"); const string fromPassword = "password"; const string subject = "test"; const string body = "Hey now!!"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = new NetworkCredential(fromAddress.Address, fromPassword), Timeout = 20000 }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With