以下是使用 C# 发送邮件的示例代码:

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

class Program
{
    static void Main(string[] args)
    {
        // 设置发件人和收件人邮箱地址
        string fromEmail = 'your_email@example.com';
        string toEmail = 'recipient_email@example.com';

        // 创建邮件对象
        MailMessage mail = new MailMessage(fromEmail, toEmail);

        // 设置邮件主题和内容
        mail.Subject = '这是一封测试邮件';
        mail.Body = '这是邮件的内容。';

        // 设置 SMTP 服务器地址和端口号
        SmtpClient smtpClient = new SmtpClient('smtp.example.com', 587);

        // 设置发件人邮箱的用户名和密码
        smtpClient.Credentials = new NetworkCredential('your_username', 'your_password');

        // 开启 SSL 加密连接
        smtpClient.EnableSsl = true;

        try
        {
            // 发送邮件
            smtpClient.Send(mail);
            Console.WriteLine('邮件发送成功。');
        }
        catch (Exception ex)
        {
            Console.WriteLine('邮件发送失败:{0}', ex.Message);
        }
    }
}

请确保替换示例代码中的以下内容:

  • 'your_email@example.com' 替换为发件人的邮箱地址。
  • 'recipient_email@example.com' 替换为收件人的邮箱地址。
  • 'smtp.example.com' 替换为您的 SMTP 服务器地址。
  • 587 替换为您的 SMTP 服务器端口号。
  • 'your_username' 替换为发件人邮箱的用户名。
  • 'your_password' 替换为发件人邮箱的密码。

请注意,使用该示例代码发送邮件需要确保您的电脑能够访问指定的 SMTP 服务器。如果使用的是公共 SMTP 服务器(例如 Gmail、Outlook 等),请确保已经正确配置了相应的 SMTP 设置。

C# 发送邮件代码示例:轻松实现邮件发送功能

原文地址: https://www.cveoy.top/t/topic/4zK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录