C#编程实现发送邮件的方法(可添加附件)
简介
在C#编程中需要经常发邮件,通常使用SMTP客户端类库实现邮件的发送。本篇攻略将详细讲解C#编程实现发送邮件的方法,并提供两个示例说明。
发送邮件的前置条件
在操作系统中需要安装SMTP服务,以用来发送邮件。常用的SMTP服务器有163邮箱、126邮箱、QQ邮箱、Gmail邮箱等,不同的邮箱提供不同的SMTP服务地址和端口。
发送邮件的步骤
- 创建SMTP客户端对象,需要提供SMTP服务器地址、端口号、用户名、密码等相关信息。
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com"; // SMTP服务器地址
client.Port = 587; // 端口号
client.EnableSsl = true; // SSL加密
client.Credentials = new NetworkCredential("username", "password"); // 邮箱登录用户名和密码
- 创建邮件对象,设置发件人信息、收件人信息、邮件主题、邮件内容等相关信息。
MailMessage message = new MailMessage();
message.From = new MailAddress("sender@gmail.com", "Sender"); // 发件人信息
message.To.Add(new MailAddress("receiver@gmail.com", "Receiver")); // 收件人信息
message.Subject = "Email subject"; // 邮件主题
message.Body = "Email body"; // 邮件内容
- 添加附件
Attachment attachment = new Attachment("attachment_file.docx");
message.Attachments.Add(attachment);
- 发送邮件
client.Send(message);
示例一:发送无附件邮件
using System.Net;
using System.Net.Mail;
namespace Test
{
public class EmailSender
{
public void SendEmail()
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("username", "password");
MailMessage message = new MailMessage();
message.From = new MailAddress("sender@gmail.com", "Sender");
message.To.Add(new MailAddress("receiver@gmail.com", "Receiver"));
message.Subject = "Email subject";
message.Body = "Email body";
client.Send(message);
}
}
}
示例二:发送带附件邮件
using System.Net;
using System.Net.Mail;
namespace Test
{
public class EmailSender
{
public void SendEmailWithAttachment()
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("username", "password");
MailMessage message = new MailMessage();
message.From = new MailAddress("sender@gmail.com", "Sender");
message.To.Add(new MailAddress("receiver@gmail.com", "Receiver"));
message.Subject = "Email subject";
message.Body = "Email body";
Attachment attachment = new Attachment("attachment_file.docx");
message.Attachments.Add(attachment);
client.Send(message);
}
}
}
以上就是C#编程实现发送邮件的方法(可添加附件)的完整攻略,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#编程实现发送邮件的方法(可添加附件) - Python技术站