C#WinForm利用SmtpClient发送Email

瘦欲@ 提交于 2020-03-19 01:29:06

      C#最初采用的是System.Web.Mail命名空间下的类发送邮件,后来经过改进,采用System.Net.Mail命名空间下的类发送邮件.当然前者仍然可用,只是后者功能更强大.

用System.Net.Mail发送邮件的原理如下:

核心就是调用SmtpClient类的send(newMessage)方法,其中的参数newMessage是一个MailMessage对象,所以我们在调用send(newMessage)方法前,须实例化MailMessage类,然后对newMessage的属性设值。

引用llsen http://hi.csdn.net/link.php?url=http://blog.csdn.net%2Fllsen

using System.Net.Mail; 
      using System.Net.Mime;
      using System.Net;
public static void CreateMessageWithAttachment(string server)
    {
       
// Specify the file to be attached and sent.
       
// This example assumes that a file named Data.xls exists in the
       
// current working directory.
        string file = @"D:\asdf.txt";
       
// Create a message and set up the recipients.
        MailMessage message = new MailMessage(
         
"asdf@163.com",
         
"asdf@163.com",
         
"test",
         
"no du");

       
// Create  the file attachment for this e-mail message.
        Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
       
// Add time stamp information for the file.
        ContentDisposition disposition = data.ContentDisposition;
        disposition.CreationDate
= System.IO.File.GetCreationTime(file);
        disposition.ModificationDate
= System.IO.File.GetLastWriteTime(file);
        disposition.ReadDate
= System.IO.File.GetLastAccessTime(file);
       
// Add the file attachment to this e-mail message.
        message.Attachments.Add(data);
       
//Send the message.
        SmtpClient client = new SmtpClient(server);
       
// Add credentials if the SMTP server requires them.
       
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
        client.UseDefaultCredentials = true;
        client.Credentials
= new System.Net.NetworkCredential("username", "password");
        client.Send(message);
       
// Display the values in the ContentDisposition for the attachment.
        ContentDisposition cd = data.ContentDisposition;
        Console.WriteLine(
"Content disposition");
        Console.WriteLine(cd.ToString());
        Console.WriteLine(
"File {0}", cd.FileName);
        Console.WriteLine(
"Size {0}", cd.Size);
        Console.WriteLine(
"Creation {0}", cd.CreationDate);
        Console.WriteLine(
"Modification {0}", cd.ModificationDate);
        Console.WriteLine(
"Read {0}", cd.ReadDate);
        Console.WriteLine(
"Inline {0}", cd.Inline);
        Console.WriteLine(
"Parameters: {0}", cd.Parameters.Count);
       
foreach (DictionaryEntry d in cd.Parameters)
        {
            Console.WriteLine(
"{0} = {1}", d.Key, d.Value);
        }
        data.Dispose();
    }

   
protected void Timer1_Tick(object sender, EventArgs e)
    {
       
if (DateTime.Now.Second % 20 == 0)
        {
            CreateMessageWithAttachment(
"smtp.163.com");
        }
    }

备注:

当使用Google-Gmail邮箱发送邮件时,Google使用了SSL(安全套接字层)加密链接。

Google的smtp服务器.Host = "smtp.gmail.com";

Google的smtp端口.Port = 587;

Google的SSL的EnableSsl必须设置为true *.EnableSsl = true;

这里再引用博客园-武广敬的一些代码,以备日后查看,谢谢

[Mail.cs]

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using log4net;
using System.Configuration;
namespace MasterSoft.WinUI
{
    
/// <summary>
    
/// 发邮件模块
    
/// Author:tonyepaper.cnblogs.com
    
/// </summary>
    public class Mail
    {
        
private string senderAddress;
        
/// <summary>
        
/// 发件人
        
/// </summary>
        public string SenderAddress
        {
            
get { return senderAddress; }
            
set { senderAddress = value; }
        }
        
private string receiverAddess;
        
/// <summary>
        
/// 收件人
        
/// </summary>
        public string ReceiverAddess
        {
            
get { return receiverAddess; }
            
set { receiverAddess = value; }
        }
        
private string subject;
        
/// <summary>
        
/// 主题
        
/// </summary>
        public string Subject
        {
            
get { return subject; }
            
set { subject = value; }
        }
        
private string body;
        
/// <summary>
        
/// 内容
        
/// </summary>
        public string Body
        {
            
get { return body; }
            
set { body = value; }
        }
        
private string smtpHost;
        
/// <summary>
        
/// SMTP主机
        
/// </summary>
        public string SmtpHost
        {
            
get { return smtpHost; }
            
set { smtpHost = value; }
        }
        
private int smtpPort;
        
/// <summary>
        
/// SMTP端口
        
/// </summary>
        public int SmtpPort
        {
            
get { return smtpPort; }
            
set { smtpPort = value; }
        }
        
private string smtpPassword;
        
/// <summary>
        
/// SMTP密码
        
/// </summary>
        public string Password
        {
            
get { return smtpPassword; }
            
set { this.smtpPassword = value; }
        }
        
/// <summary>
        
/// 从配置文件中读出SMTP相关信息
        
/// </summary>
        public Mail()
        {
            senderAddress 
= ConfigurationManager.AppSettings["SmtpUser"];
            smtpPassword 
= ConfigurationManager.AppSettings["SmtpPassword"];
            smtpHost 
= ConfigurationManager.AppSettings["SmtpHost"];
            smtpPort 
= Int32.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
        }
        
/// <summary>
        
/// 邮件
        
/// </summary>
        
/// <param name="receiverAddess">收件人地址</param>
        
/// <param name="subject">主题</param>
        
/// <param name="body">内容</param>
        public Mail(string receiverAddess, string subject, string body):this()
        {
            
this.receiverAddess = receiverAddess;
            
this.subject = subject;
            
this.body = body;
        }
        
/// <summary>
        
/// 发送邮件
        
/// </summary>
        public bool Send()
        {
            MailMessage mailMessage 
= new MailMessage(senderAddress, receiverAddess);
            mailMessage.Subject 
= subject;
            mailMessage.Body 
= body;

            SmtpClient smtpClient 
= new SmtpClient(smtpHost, smtpPort);
            //使用SSL加密连线
            smtpClient.EnableSsl=true;
            NetworkCredential networkCredential 
= new NetworkCredential(senderAddress, smtpPassword);
            smtpClient.Credentials 
= networkCredential;
            
try
            {
                smtpClient.Send(mailMessage);
                
return true;
            }
            
catch (Exception ex)
            {
                
return false;
            }
        }
    }
}

 

发现一个问题.如果使用465端口就会发生超时的错误.使用587就不会.奇怪.不过使用FoxMail来用465端口发信就正常.知道原因的请指点一下.谢谢!

 

[App.config]
      <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  
<appSettings>
    
<add key="SmtpHost" value="smtp.gmail.com"/>
    
<add key="SmtpPort" value="587"/>
    
<add key="SmtpUser" value="tonyxxx@gmail.com"/>
    
<add key="SmtpPassword" value="*******"/>
  
</appSettings>
</configuration>

尽管设置了这些,但我个人测试的C#写的Gmail的客户端貌似还发送不了邮件,真不知道什么原因。

郁闷,如有人知道为什么,请告诉我;如有源代码更好,我的个人Email兼MSN:hn-zjf@hotmail.com

发过来一份参考下,谢谢。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!