在C#中使用SMTP发送电子邮件可以通过以下步骤实现:
using System.Net;
using System.Net.Mail;
SmtpClient client = new SmtpClient();
client.Host = "SMTP服务器地址";
client.Port = SMTP服务器端口号;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("发件人邮箱", "发件人邮箱密码");
MailMessage message = new MailMessage();
message.From = new MailAddress("发件人邮箱");
message.To.Add("收件人邮箱");
message.Subject = "邮件主题";
message.Body = "邮件正文";
message.IsBodyHtml = true; // 如果要发送HTML格式的邮件,设置为true
client.Send(message);
完整的代码示例:
using System;
using System.Net;
using System.Net.Mail;
namespace EmailSender
{
class Program
{
static void Main(string[] args)
{
try
{
SmtpClient client = new SmtpClient();
client.Host = "SMTP服务器地址";
client.Port = SMTP服务器端口号;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("发件人邮箱", "发件人邮箱密码");
MailMessage message = new MailMessage();
message.From = new MailAddress("发件人邮箱");
message.To.Add("收件人邮箱");
message.Subject = "邮件主题";
message.Body = "邮件正文";
message.IsBodyHtml = true;
client.Send(message);
Console.WriteLine("邮件发送成功!");
}
catch (Exception ex)
{
Console.WriteLine("邮件发送失败:" + ex.Message);
}
}
}
}
请注意,上述代码中的SMTP服务器地址、端口号、发件人邮箱、发件人邮箱密码、收件人邮箱、邮件主题和正文需要根据实际情况进行替换。
推荐的腾讯云相关产品:腾讯云邮件推送(https://cloud.tencent.com/product/ses)
领取专属 10元无门槛券
手把手带您无忧上云