下面是使用ASP.NET发送电子邮件到Gmail账户的代码示例:
using System;
using System.Net;
using System.Net.Mail;
namespace EmailExample
{
class Program
{
static void Main(string[] args)
{
// 发送方的电子邮件和密码
string senderEmail = "your_email@gmail.com";
string senderPassword = "your_password";
// 第一个电子邮件的收件人和内容
string recipientEmail1 = "recipient1@gmail.com";
string subject1 = "Hello from ASP.NET";
string body1 = "This is the first email sent using ASP.NET.";
// 第二个电子邮件的收件人和内容
string recipientEmail2 = "recipient2@gmail.com";
string subject2 = "Hello again";
string body2 = "This is the second email sent using ASP.NET.";
// 创建SMTP客户端
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
try
{
// 发送第一个电子邮件
MailMessage message1 = new MailMessage(senderEmail, recipientEmail1, subject1, body1);
client.Send(message1);
Console.WriteLine("First email sent successfully.");
// 发送第二个电子邮件
MailMessage message2 = new MailMessage(senderEmail, recipientEmail2, subject2, body2);
client.Send(message2);
Console.WriteLine("Second email sent successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error sending email: " + ex.Message);
}
}
}
}
请确保将your_email@gmail.com
和your_password
替换为您自己的Gmail帐户电子邮件和密码。请注意,这段代码使用了Gmail的SMTP服务器,并且要求您的Gmail帐户启用了SMTP访问权限。
此代码将创建一个SMTP客户端并发送两个独立的电子邮件到不同的Gmail收件人。第一个电子邮件的主题是"Hello from ASP.NET",内容是"This is the first email sent using ASP.NET."。第二个电子邮件的主题是"Hello again",内容是"This is the second email sent using ASP.NET."。
如果发送成功,控制台将显示"First email sent successfully."和"Second email sent successfully."。如果发送过程中出现错误,控制台将显示错误消息。