C#实现用免费smtp服务器(GMail)发邮件

本文介绍了如何使用C#和Gmail API通过SMTP发送邮件的基本步骤,包括创建邮件消息对象、设置发件人、收件人、主题、正文等,并通过配置SSL连接和提供用户名及密码来实现邮件发送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Method 1
  ------------------------------------------------------------------------------------------------------
  // using System.Net.Mail;
  Mailmessageage message = new Mailmessageage();
  message.From = new MailAddress("User@gmail.com", "Your DisplayName");
  message.To.Add(new MailAddress("To@gmail.com")); // the email you want to send email to
  message.Subject = "A test email"
  
  message.IsBodyHtml = true;
  message.BodyEncoding = System.Text.Encoding.UTF8;
  message.Body = "this is just a simple test!<br> Jack"
  message.Priority = MailPriority.High;
  
  SmtpClient client = new SmtpClient("smtp.gmail.com", 587); // 587;//Gmail使用的端口
  client.Credentials = new System.Net.NetworkCredential("User@gmail.com", "*****"); // Your user name & password
  client.EnableSsl = true; //经过ssl加密
  object userState = message;
  try
  {
  client.Send(message);
  Response.Write("邮件发送到" + message.To.ToString() + "<br>");
  }
  catch (Exception ee)
  {
  Response.Write(ee.messageage + "<br>" + ee.InnerException.messageage);
  }
  
  Method 2
  ------------------------------------------------------------------------------------------------------
  
  // http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx
  // using System.Net.Mail;
  MailMessage message = new MailMessage();
  message.From = new MailAddress("User@gmail.com");
  
  message.To.Add(new MailAddress("to@gmail.com"));
  
  message.Subject = "This is my subject"
  message.Body = "This is the content"
  SmtpClient client = new SmtpClient();
  client.EnableSsl = true;
  
  try
  {
  client.Send(message);
  Response.Write("邮件发送到" + message.To.ToString() + "<br>");
  }
  catch (Exception ee)
  {
  Response.Write(ee.Message );
  }
  
  //In web.config
  
  <system.net>
  <mailSettings>
  <smtp from="from@gmail.com">
  <network host="smtp.gmail.com" port="587" userName="User@gmail.com" password="your pwd" />
  <!-- if has 'defaultCredentials="true"' , using Gmail can not send success -->
  </smtp>
  </mailSettings>
  </system.net>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值