溫馨提示×

C#中SMTP郵件主題和內(nèi)容如何編寫

c#
小樊
84
2024-08-18 05:08:38
欄目: 編程語言

在C#中發(fā)送SMTP郵件時,可以使用以下代碼示例來編寫郵件主題和內(nèi)容:

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

class Program
{
    static void Main()
    {
        // 發(fā)件人郵箱和密碼
        string from = "your_email@example.com";
        string password = "your_password";

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

        // SMTP服務(wù)器地址和端口
        string smtpAddress = "smtp.example.com";
        int portNumber = 587;

        // 創(chuàng)建郵件對象
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(from);
        mail.To.Add(to);
        mail.Subject = "郵件主題";
        mail.Body = "郵件內(nèi)容";

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

        // 發(fā)送郵件
        smtp.Send(mail);

        Console.WriteLine("郵件發(fā)送成功!");
    }
}

在上面的示例中,需要替換from、password、to、smtpAddress等變量的值為實際的發(fā)件人、收件人郵箱以及SMTP服務(wù)器信息。郵件主題和內(nèi)容分別設(shè)置在mail.Subjectmail.Body屬性中。發(fā)送郵件時,調(diào)用smtp.Send(mail)方法即可將郵件發(fā)送出去。

0