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 = "[email protected]";
            string fromMailAddress = "[email protected]";
            string subjectInfo = "My First Email";
            string bodyInfo [email protected]"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;           //发件箱的用户名(即@符号前面的字符串,例如:[email protected],用户名为: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">发件箱的用户名(即@符号前面的字符串,例如:[email protected],用户名为: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)

时间: 2024-08-07 18:16:30

c# 发送邮件、附件的相关文章

C# 发送邮件 附件名称为空

 示例代码: // 1.创建邮件 MailMessage mailMsg = new MailMessage(); mailMsg.To.Add(new MailAddress("[email protected]")); // 2.设置邮件标题.正文等信息 mailMsg.HeadersEncoding = Encoding.GetEncoding("gb2312"); mailMsg.SubjectEncoding = Encoding.GetEncoding(

Linux使用Mutt发送邮件/附件

使用Mutt发邮件极其方便,只需要一条命令即可发送或者批量发送邮件 功能说明:E-mail管理程序. 语 法:mutt [-hnpRvxz][-a<文件>][-b<地址>][-c<地址>][-f<邮件文件>][-F<配置文件>][-H<邮件草稿>][-i<文件>][-m<类型>][-s<主题>][邮件地址] 补充说明:mutt是一个文字模式的邮件管理程序,提供了全屏幕的操作界面. 参 数: -a&l

Java mail发送邮件附件出现.eml文件夹

在使用JAVA MAIL发送邮件时,163邮箱和QQ邮箱收到PDF附件,格式错误如下图: 163邮箱: QQ邮箱: 经历了很长时间的研究和测试,错误原因为在邮件正文和邮件附件用的MimeBodyPart对象是同一个,进而导致上述现象,解决办法为正文是一个MimeBodyPart对象,一个附件是一个MimeBodyPart对象.正确代码如下: 原文地址:https://www.cnblogs.com/XH09/p/10981329.html

javaVuser——javamail发送邮件+附件

调试过程中遇到的问题: 1.权限验证不通过 props.put("mail.smtp.auth","true"); 2.附件乱码 bp.setFileName(MimeUtility.encodeText(fileds.getName(),"utf-8",null));//取附件要这样写,不然附件名会乱码.

python给多个发送邮件附件,参考于《python自动化运维》

#!/usr/bin/env python #coding: utf-8 #author:luodi date:2015/02/12 #description:this is a send mail script import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText #定义SMTP服务器及相关信息 HOST = "smtp.exmail.qq.com&q

C++发送邮件和附件

c++socketnulldelete服务器stream 头文件 [cpp] view plaincopy /*********************************************************************** *发送邮件模块头文件 *可以发送文本和附件(支持多个附件一起发送) *************************************************************************/ #pragma once s

c++使用stmp协议发送邮件(163的邮箱,TTL非SSL)

0.有关TLS和SSL SSL/TLS是用来加密邮件流的.如果不加密的话很容易被人破解. 不过既然是要发送广告邮件,这个就不用在意了,使用没加密的就行. 另外在使用的时候,发现,qq的邮箱需要使用SSL才能连接上,这个再以后需要用qq发群邮件的时候再来处理,这里暂时只是使用163的邮箱,作为发送端 1.主要的类 SendMail.h: /*********************************************************************** *发送邮件模块头

邮件正文及其附件的发送的C++实现

 这段代码我花了整整一天来编写,如果转载,请注明出处,谢谢!    前面的一篇文章已经讲了如何发送邮件正文,原理我就不再叙述了,要了解的同学请到这里查看!    http://blog.csdn.net/lishuhuakai/article/details/27503503    网上很多发送邮件附件的代码都不能用,所以我用心写了一个,直接封装成了一个类,需要的同学可以直接调用这个类来发送邮件,使用的是纯C++,不含MFC,请放心使用.(在VS2013下测试完美通过!)    废话不多说,直接

解读Python发送邮件

解读Python发送邮件 Python发送邮件需要smtplib和email两个模块.也正是由于我们在实际工作中可以导入这些模块,才使得处理工作中的任务变得更加的简单.今天,就来好好学习一下使用Python发送邮件吧. SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件.HTML邮件以及带附件的邮件. Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件. 1.邮件正文是文本的格式 1 # -*- codi

发送邮件的小功能(.net core 版)

前言: 使用.net core 开发有一段时间了,期间从.net core 2.0 preview1 到 preview2 又到core 1.1 现在2.0正式版出来了.又把项目升级至2.0了.目前正在用2.0进行开发.期间也遇到了不少问题.在这里进行总结一下. 最近工作内容就是job的迁移工作,从Framework迁移到.net Core上.体会到了两个框架的不同之处.以及使用过程中体会到的1.1和2.0的不同 以及Framework和Core的不同.首先说一下2.0和Framework的不同