C# send mail office365
To send an email using Office 365 in C#, you'll need to use the System.Net.Mail
namespace and configure your email settings. Here's a step-by-step guide:
Step 1: Install the required NuGet package
In your C# project, install the System.Net.Mail
NuGet package by running the following command in the Package Manager Console:
Install-Package System.Net.Mail
Step 2: Configure your email settings
Create a new class to hold your email settings:
public class EmailSettings
{
public string SmtpServer { get; set; }
public int SmtpPort { get; set; }
public string EmailAddress { get; set; }
public string EmailPassword { get; set; }
}
Configure your email settings with your Office 365 credentials:
EmailSettings settings = new EmailSettings
{
SmtpServer = "outlook.office365.com",
SmtpPort = 587,
EmailAddress = "your_email_address@your_domain.com",
EmailPassword = "your_email_password"
};
Step 3: Create a new MailMessage object
Create a new MailMessage
object to hold the email details:
MailMessage mail = new MailMessage();
Set the From
address, To
address, and subject:
mail.From = new MailAddress(settings.EmailAddress);
mail.To.Add("recipient_email_address@recipient_domain.com");
mail.Subject = "Test Email";
Step 4: Add the email body
Add the email body using the Body
property:
mail.Body = "This is a test email sent using Office 365 in C#.";
Step 5: Send the email
Use the SmtpClient
class to send the email:
SmtpClient client = new SmtpClient();
client.Host = settings.SmtpServer;
client.Port = settings.SmtpPort;
client.EnableSsl = true;
client.Credentials = new NetworkCredential(settings.EmailAddress, settings.EmailPassword);
client.Send(mail);
Full code example
Here's the complete code example:
using System;
using System.Net.Mail;
public class EmailSender
{
public void SendEmail()
{
EmailSettings settings = new EmailSettings
{
SmtpServer = "outlook.office365.com",
SmtpPort = 587,
EmailAddress = "your_email_address@your_domain.com",
EmailPassword = "your_email_password"
};
MailMessage mail = new MailMessage();
mail.From = new MailAddress(settings.EmailAddress);
mail.To.Add("recipient_email_address@recipient_domain.com");
mail.Subject = "Test Email";
mail.Body = "This is a test email sent using Office 365 in C#.";
SmtpClient client = new SmtpClient();
client.Host = settings.SmtpServer;
client.Port = settings.SmtpPort;
client.EnableSsl = true;
client.Credentials = new NetworkCredential(settings.EmailAddress, settings.EmailPassword);
client.Send(mail);
}
}
Note: Make sure to replace the placeholders (your_email_address@your_domain.com
and your_email_password
) with your actual Office 365 credentials.