NET 使用SmtpClient 发送邮件

以下是一个使用.NET 8 使用SmtpClient 发送邮件到QQ 邮箱的示例代码


using System;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace EmailDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 邮箱配置
            string senderEmail = "your_email@qq.com";
            string senderPassword = "your_password";
            string receiverEmail = "receiver_email@qq.com";
            
            // 邮件内容
            string subject = "测试邮件";
            string body = "这是一封测试邮件。";

            // 创建SMTP客户端
            SmtpClient client = new SmtpClient("smtp.qq.com", 587);
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential(senderEmail, senderPassword);

            // 创建邮件消息
            MailMessage message = new MailMessage(senderEmail, receiverEmail, subject, body);
            message.SubjectEncoding = Encoding.UTF8;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = false;

            try
            {
                client.Send(message);
                Console.WriteLine("邮件发送成功!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"邮件发送失败:{ex.Message}");
            }
        }
    }
}

请注意,你需要将代码中的”your_email@qq.com” 和”your_password”替换为你自己的QQ 邮箱地址
和密码或授权码。另外,需要确保你的QQ 邮箱已开启SMTP 服务,并且允许使用第三方客户端发送邮件。

© 版权声明

相关文章

暂无评论

none
暂无评论...