c# 发送邮件、附件

WinForm窗体代码如下:

<span style="font-size:14px;">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
<span style="color:#ff0000;">//要添加的引用如下</span>
using System.Net.Mail;
using System.Net.Mime;
using System.Timers;
using System.IO;

namespace NovelCS {
    public partial class Form3 : Form {
        public Form3() {
            InitializeComponent();
        }
           
        private void Form3_Load(object sender, EventArgs e) {
            //一些常见的发送邮件服务器地址 一般都是 stmp.**.com   **=qq 或 126 或163 或 gmail 有例外的,具体问度娘

            string senderServerIp = "smtp.qq.com";           
            string toMailAddress = "1449740504@qq.com";
            string fromMailAddress = "1449740504@qq.com";
            string subjectInfo = "My First Email";
            string bodyInfo =@"Hello Jackerson, \r\n
                                        This is my first testing e_mail.But what all thess is from  an author named Eric Sun.
                                        Thank you,Eric Sun.";
            string mailUsername = "1449740504";
            string mailPassword = "******"; //发送人邮箱的密码
            string mailPort = "25";   //邮箱端口号
            string attachPath = "D:\\jsj.txt; D:\\jsj2.txt";//附件本地地址

            MyEmail email = new MyEmail(senderServerIp, toMailAddress, fromMailAddress, subjectInfo, bodyInfo, mailUsername, mailPassword, mailPort, false, false);
            email.AddAttachments(attachPath);
            email.Send();
        }
               
    }

    public class MyEmail {
        private MailMessage me;//主要处理发送邮件的内容,例:收发件人地址、标题、主体、图片
        private SmtpClient sc;   //主要处理用smtp发送邮件的配置信息,例:发送邮件服务器地址、发送端口号、验证方式
        private int mSenderPort;                         //发送邮件所用的端口号(htmp协议默认为25)
        private string mSenderServerHost;          //发件箱的邮件服务器地址(IP形式或字符串形式均可)
        private string mSenderUserName;           //发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)
        private string mSenderPassword;             //发件箱的密码
        private bool mEnableSsl;                         //是否对邮件内容进行socket层加密传输
        private bool mEnablePwdAuthentication;  //是否对发件人邮箱进行密码验证

        ///<summary>
        /// <strong><span style="color:#ff0000;">构造函数</span></strong>
        ///</summary>
        ///<param name="server">发件箱的邮件服务器地址</param>
        ///<param name="toMail">收件人地址(可以是多个收件人,程序中是以“;"进行区分的)</param>
        ///<param name="fromMail">发件人地址</param>
        ///<param name="subject">邮件标题</param>
        ///<param name="emailBody">邮件内容(可以以html格式进行设计)</param>
        ///<param name="username">发件箱的用户名(即@符号前面的字符串,例如:hello@163.com,用户名为:hello)</param>
        ///<param name="password">发件人邮箱密码</param>
        ///<param name="port">发送邮件所用的端口号(htmp协议默认为25)</param>
        ///<param name="sslEnable">true表示对邮件内容进行socket层加密传输,false表示不加密</param>
        ///<param name="pwdCheckEnable">true表示对发件人邮箱进行密码验证,false表示不对发件人邮箱进行密码验证</param>
        public MyEmail(string server, string toMailAddress, string fromMailAddress, string emailTitle, string emailBody, string username, string password, string port, bool sslEnable, bool pwdCheckEnable) {
            try {
                me = new MailMessage();
                me.To.Add(toMailAddress);
                me.From = new MailAddress(fromMailAddress);
                me.Subject = emailTitle;
                me.Body = emailBody;
                me.IsBodyHtml = true;
                me.BodyEncoding = System.Text.Encoding.UTF8;
                me.Priority = MailPriority.Normal;
                this.mSenderServerHost = server;
                this.mSenderUserName = username;
                this.mSenderPassword = password;
                this.mSenderPort = Convert.ToInt32(port);
                this.mEnableSsl = sslEnable;
                this.mEnablePwdAuthentication = pwdCheckEnable;
            } catch (Exception ex) {
                MessageBox.Show(ex.ToString());
            }
        }

        ///<summary>
        /// <strong><span style="color:#ff0000;">添加附件</span></strong>
        ///</summary>
        ///<param name="attachmentsPath">附件的路径集合,以分号分隔</param>
        public void AddAttachments(string attachmentsPath) {
            try {
                string[] path = attachmentsPath.Split(';'); //以什么符号分隔可以自定义
                Attachment data;
                ContentDisposition disposition;
                for (int i = 0; i < path.Length; i++) {
                    data = new Attachment(path[i], MediaTypeNames.Application.Octet);
                    disposition = data.ContentDisposition;
                    disposition.CreationDate = File.GetCreationTime(path[i]);
                    disposition.ModificationDate = File.GetLastWriteTime(path[i]);
                    disposition.ReadDate = File.GetLastAccessTime(path[i]);
                    me.Attachments.Add(data);
                }
            } catch (Exception ex) {
                MessageBox.Show(ex.ToString());
            }
        }


        ///<summary>
        /// <strong><span style="color:#ff0000;">邮件的发送</span></strong>
        ///</summary>
        public void Send() {
            try {
                if (me != null) {
                    sc = new SmtpClient();
                    //mSmtpClient.Host = "smtp." + mMailMessage.From.Host;
                    sc.Host = this.mSenderServerHost;
                    sc.Port = this.mSenderPort;
                    sc.UseDefaultCredentials = false;
                    sc.EnableSsl = this.mEnableSsl;
                    if (this.mEnablePwdAuthentication) {
                        System.Net.NetworkCredential nc = new System.Net.NetworkCredential(this.mSenderUserName, this.mSenderPassword);
                        //mSmtpClient.Credentials = new System.Net.NetworkCredential(this.mSenderUsername, this.mSenderPassword);
                        //NTLM: Secure Password Authentication in Microsoft Outlook Express
                        sc.Credentials = nc.GetCredential(sc.Host, sc.Port, "NTLM");
                    } else {
                        sc.Credentials = new System.Net.NetworkCredential(this.mSenderUserName, this.mSenderPassword);
                    }
                    sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    sc.Send(me);
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }

    }      
      
}</span>

备注:

(1)经过测试,确实可以使用。

(2)本文出处:Eric Sun(http://www.cnblogs.com/mingmingruyuedlut/archive/2011/10/14/2212255.html)

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用C#编写的控制台程序,用于发送邮件: ```csharp using System; using System.Net; using System.Net.Mail; class Program { static void Main(string[] args) { // 设置邮件服务器 string smtpServer = args[0]; int smtpPort = 25; SmtpClient client = new SmtpClient(smtpServer, smtpPort); // 设置发件人 string from = args[1]; string displayName = args[2]; MailAddress fromAddress = new MailAddress(from, displayName); // 设置收件人 string to = args[3]; MailAddress toAddress = new MailAddress(to); // 创建邮件对象 MailMessage message = new MailMessage(fromAddress, toAddress); // 设置抄送和密送 if (args.Length > 4) { string[] cc = args[4].Split(','); foreach (string c in cc) { message.CC.Add(c); } } if (args.Length > 5) { string[] bcc = args[5].Split(','); foreach (string b in bcc) { message.Bcc.Add(b); } } // 设置主题和内容 message.Subject = args[6]; message.Body = args[7]; // 添加附件 if (args.Length > 8) { string[] attachments = args[8].Split(','); foreach (string attachment in attachments) { Attachment file = new Attachment(attachment); message.Attachments.Add(file); } } // 发送邮件 client.Send(message); Console.WriteLine("邮件发送成功!"); } } ``` 在命令行中输入以下命令即可发送邮件: ``` SendMail 邮件服务器IP 发件人 显示名称 收件人 抄送 密送 主题 内容 文件 ``` 其中,邮件服务器IP、发件人、显示名称、收件人、主题和内容是必填项,抄送、密送和文件是可选项。如果有多个收件人、抄送或密送,可以用逗号分隔。如果有多个文件,也可以用逗号分隔。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值