C# 发送电子邮件:使用 SmtpClient 类实现邮件发送
要在 C# 中发送电子邮件,可以使用'System.Net.Mail'命名空间中的'SmtpClient'类。下面是一个发送电子邮件的示例代码:
using System;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main(string[] args)
{
// 设置发件人和收件人信息
string from = 'your_email@example.com';
string to = 'recipient_email@example.com';
string subject = 'Hello from C#';
string body = 'This is a test email sent from C#.';
// 创建SmtpClient对象
SmtpClient smtpClient = new SmtpClient('smtp.example.com', 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential('your_email@example.com', 'your_password');
// 创建MailMessage对象
MailMessage mailMessage = new MailMessage(from, to, subject, body);
try
{
// 发送邮件
smtpClient.Send(mailMessage);
Console.WriteLine('Email sent successfully.');
}
catch (Exception ex)
{
Console.WriteLine('Failed to send email. Error message: ' + ex.Message);
}
}
}
在上面的代码中,需要将以下值替换为真实的信息:
- 'from':发件人的电子邮件地址
- 'to':收件人的电子邮件地址
- 'subject':邮件主题
- 'body':邮件正文
- 'smtpClient.Host':SMTP服务器的主机名
- 'smtpClient.Port':SMTP服务器的端口号
- 'smtpClient.Credentials':发件人的电子邮件地址和密码
请确保在使用实际的电子邮件地址和密码之前,仔细检查和测试代码。
原文地址: https://www.cveoy.top/t/topic/Uki 著作权归作者所有。请勿转载和采集!