C# 发送电子邮件:完整指南及代码示例
以下是 C# 中发送电子邮件的示例代码:
using System.Net.Mail;
public void SendEmail()
{
string fromAddress = 'your_email_address';
string toAddress = 'recipient_email_address';
string subject = 'email_subject';
string body = 'email_body';
string smtpServer = 'smtp_server_address';
int smtpPort = 587; // 默认 SMTP 端口为 587
// 创建一个新的 MailMessage 对象
MailMessage message = new MailMessage(fromAddress, toAddress, subject, body);
// 设置额外的邮件属性,例如 CC 和 BCC 收件人
message.CC.Add('cc_recipient_email_address');
message.Bcc.Add('bcc_recipient_email_address');
// 创建一个新的 SmtpClient 对象
SmtpClient client = new SmtpClient(smtpServer, smtpPort);
// 设置客户端凭据,如果需要
client.Credentials = new System.Net.NetworkCredential('smtp_username', 'smtp_password');
// 启用 SSL 加密,如果需要
client.EnableSsl = true;
// 发送电子邮件
client.Send(message);
}
注意:
在使用此代码之前,您需要替换示例中的电子邮件地址、SMTP 服务器地址、用户名和密码等信息。此外,您可能需要在代码中添加异常处理,以处理电子邮件发送期间可能出现的错误。
配置步骤:
- 获取 SMTP 服务器地址和端口: 您的电子邮件提供商(例如 Gmail、Outlook)会提供这些信息。
- 设置凭据: 如果需要身份验证,您需要设置 SMTP 用户名和密码。
- 启用 SSL: 许多电子邮件服务提供商要求使用 SSL 加密来保护电子邮件传输。
安全建议:
- 不要将敏感信息(例如密码)直接硬编码到代码中。
- 使用环境变量或配置文件存储这些信息。
- 考虑使用第三方库来简化电子邮件发送过程,并提供更好的安全性。
更多信息:
希望本文能够帮助您在 C# 中发送电子邮件。如果您有任何问题或建议,请随时留言。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/oxBx 著作权归作者所有。请勿转载和采集!