阅读量:0
在C#中使用SMTP发送邮件可以通过以下步骤:
- 引用System.Net和System.Net.Mail命名空间
using System.Net; using System.Net.Mail;
- 创建SmtpClient实例并设置SMTP服务器、端口号和凭据信息
SmtpClient client = new SmtpClient("smtp.example.com", 587); client.Credentials = new NetworkCredential("your_email@example.com", "your_password"); client.EnableSsl = true;
- 创建MailMessage实例并设置发件人、收件人、主题和正文内容
MailMessage message = new MailMessage(); message.From = new MailAddress("your_email@example.com"); message.To.Add("recipient@example.com"); message.Subject = "Subject"; message.Body = "Body";
- 发送邮件
client.Send(message);
完整的示例代码如下:
using System; using System.Net; using System.Net.Mail; class Program { static void Main() { SmtpClient client = new SmtpClient("smtp.example.com", 587); client.Credentials = new NetworkCredential("your_email@example.com", "your_password"); client.EnableSsl = true; MailMessage message = new MailMessage(); message.From = new MailAddress("your_email@example.com"); message.To.Add("recipient@example.com"); message.Subject = "Subject"; message.Body = "Body"; client.Send(message); Console.WriteLine("Email sent successfully."); } }
请注意,您需要替换示例中的SMTP服务器、邮箱地址、密码、收件人地址、主题和正文内容为实际的信息。另外,有些SMTP服务器可能需要额外的配置才能成功发送邮件,如授权码或不同的端口号等。