温馨提示×

C#中SMTP邮件主题和内容如何编写

c#
小樊
84
2024-08-18 05:08:38
栏目: 编程语言

在C#中发送SMTP邮件时,可以使用以下代码示例来编写邮件主题和内容:

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

class Program
{
    static void Main()
    {
        // 发件人邮箱和密码
        string from = "your_email@example.com";
        string password = "your_password";

        // 收件人邮箱
        string to = "recipient@example.com";

        // SMTP服务器地址和端口
        string smtpAddress = "smtp.example.com";
        int portNumber = 587;

        // 创建邮件对象
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(from);
        mail.To.Add(to);
        mail.Subject = "邮件主题";
        mail.Body = "邮件内容";

        // 设置SMTP客户端
        SmtpClient smtp = new SmtpClient(smtpAddress, portNumber);
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential(from, password);
        smtp.EnableSsl = true;

        // 发送邮件
        smtp.Send(mail);

        Console.WriteLine("邮件发送成功!");
    }
}

在上面的示例中,需要替换frompasswordtosmtpAddress等变量的值为实际的发件人、收件人邮箱以及SMTP服务器信息。邮件主题和内容分别设置在mail.Subjectmail.Body属性中。发送邮件时,调用smtp.Send(mail)方法即可将邮件发送出去。

0