To send an email using .NET Core, you can use the built-in SmtpClient
class from the System.Net.Mail
namespace. Before proceeding, make sure you have installed the required NuGet package for this functionality. In .NET Core, you can use the System.Net.Mail
package. To install it, run the following command in the Package Manager Console:
Install-Package System.Net.Mail
using System;
using System.Net;
using System.Net.Mail;
namespace EmailSender
{
class Program
{
static void Main(string[] args)
{
try
{
// Sender and recipient email addresses
string senderEmail = "your_email@gmail.com";
string recipientEmail = "recipient@example.com";
// Set up the SMTP client
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("your_email@gmail.com", "your_email_password");
// Create the email message
MailMessage mailMessage = new MailMessage(senderEmail, recipientEmail);
mailMessage.Subject = "Test Email from .NET Core";
mailMessage.Body = "This is a test email sent from .NET Core.";
// Send the email
smtpClient.Send(mailMessage);
Console.WriteLine("Email sent successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error sending email: " + ex.Message);
}
}
}
}
Replace "your_email@gmail.com"
and "your_email_password"
with your actual Gmail email and password or use the appropriate credentials for your email provider. Note that using the sender's email and password directly in the code may not be secure in a production environment, so consider using environment variables or configuration files to store sensitive information.
Also, keep in mind that some email providers may require additional settings or app-specific passwords for using SMTP. For Gmail, you may need to enable "Allow less secure apps" or generate an "App Password" if you have two-factor authentication enabled.
Once the email is sent successfully, you should see the message "Email sent successfully" in the console.
No comments:
Post a Comment