欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#编写发送邮件组件

程序员文章站 2023-12-01 15:49:04
在mailsetting里的配置好邮件服务器,然后mailentity里配置好要发送的邮件主体,最后使用mailserver里的方法send发送邮件 mailentity...

在mailsetting里的配置好邮件服务器,然后mailentity里配置好要发送的邮件主体,最后使用mailserver里的方法send发送邮件

mailentity.cs

using system;
using system.collections.generic;
using system.linq;
using system.web;
 
namespace autooutticket.mail
{
  public class mailentity
  {
    public string from;
    public string to;
    public string fromname;
    public string toname;
    public string cc;
    public bool ishtml;
    public string subject;
    public string body;
    public string attach;
  }
}

mailserver.cs

using system;
using system.collections.generic;
using system.linq;
using system.net;
using system.net.mail;
using system.web;
 
namespace autooutticket.mail
{
  public class mailserver
  {
    mailentity _entity = null;
    mailsetting _settings = null;
    public mailserver(mailentity entity, mailsetting settings)
    {
      this._entity = entity;
      this._settings = settings;
    }
    public bool send()
    {
      try
      {
        mailmessage message = new mailmessage(_settings.smtpuser, _entity.to);
        message.isbodyhtml = _entity.ishtml;
        message.subject = _entity.subject;
        message.body = _entity.body;
        if (!string.isnullorwhitespace(_entity.cc))
        {
          message.cc.add(_entity.cc);
        }
        if (!string.isnullorwhitespace(_entity.attach))
        {
          attachment atta=new attachment(_entity.attach);
          message.attachments.add(atta);
        }
 
        smtpclient client = new smtpclient(_settings.smtphost, _settings.smtpport);
        client.credentials = new networkcredential(_settings.smtpuser, _settings.smtppass);
 
        client.sendasync(message, null);
 
        return true;
      }
      catch (exception)
      {
      }
      return false;
    }
  }
}

mailsetting.cs

using system;
using system.collections.generic;
using system.linq;
using system.web;
 
namespace autooutticket.mail
{
  public class mailsetting
  {
    public string smtphost = "";
    public int smtpport;
    public string smtpuser = "";
    public string smtppass = "";
    public mailsetting()
    {
    }
    public mailsetting(string smtpserver, int smtpport, string smtpuser, string smtppass)
    {
      this.smtphost = smtpserver;
      this.smtpport = smtpport;
      this.smtpuser = smtpuser;
      this.smtppass = smtppass;
    }
  }
}

以上所述就是本文的全部内容了,希望大家能够喜欢。