c# 发送邮件
以下是使用C#发送邮件的示例代码:
using System.Net;
using System.Net.Mail;
class Program
{
static void Main(string[] args)
{
// 发件人邮箱地址
string from = "example@gmail.com";
// 发件人邮箱密码
string password = "password";
// 收件人邮箱地址
string to = "example@qq.com";
// 邮件主题
string subject = "Test email";
// 邮件内容
string body = "This is a test email.";
// 创建Smtp客户端
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
// 设置Smtp客户端的凭证
client.Credentials = new NetworkCredential(from, password);
// 启用SSL加密
client.EnableSsl = true;
// 创建MailMessage对象
MailMessage message = new MailMessage(from, to, subject, body);
// 设置邮件的编码格式
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.BodyEncoding = System.Text.Encoding.UTF8;
// 设置邮件的优先级
message.Priority = MailPriority.Normal;
try
{
// 发送邮件
client.Send(message);
Console.WriteLine("邮件发送成功!");
}
catch (Exception ex)
{
Console.WriteLine("邮件发送失败,原因:" + ex.Message);
}
}
}
注意事项:
- 发件人邮箱需要开启SMTP服务,并生成授权码。
- Smtp客户端需要指定SMTP服务器地址和端口号。
- MailMessage对象需要指定发件人、收件人、主题和内容等信息
原文地址: https://www.cveoy.top/t/topic/frUG 著作权归作者所有。请勿转载和采集!