您现在的位置: 万盛学电脑网 >> 程序编程 >> 网络编程 >> .net编程 >> 正文

C#控制台程序,发送邮件,可带附件的代码!

作者:佚名    责任编辑:admin    更新时间:2022-06-22

class="area">

最近几天由于公司发送了大量内容相同的邮件,而被国外的反垃圾邮件组织列入了黑名单,致使很多客户收不到我们的邮件,客服接到投诉,而之前做的一个查询日志的小页面,因为某种原因,访问速度很慢,甚至这几天人一多,页面就总是超时.刚开始以为是程序问题或者是数据量比较大,但是程序也只是一句简单的两表联查,两张表大概也就200W左右的数据,在线下跑的时候速度很快,可是一到线上就慢了很多.后来到系统组那边找了一下,发现是线上的机器在连数据库的时候,没有将数据库的IP添加到Host里,添进去之后速度瞬间就提了上去.
    昨天在研究解决策略的时候,同事建议建立一个定时任务,将查询的结果以附件的形式发送给查询人,所以写了一个控制台程序来跑.因为以前没有接触过这方面的东西,所以查了很多,最后还是发现MSDN真是个好东西,呵呵,不说了,代码帖上来,大家把***换成自己的邮件服务器,然后发件人和收件人相应地改一下,程序就可以跑了.有什么问题还请大家积极地反应,帮助小弟提高.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
using System.Net;
using System.Net.Mime;
using System.Net.Mail;

namespace SendEmail
{
    class Program
    {
        //smtp.UseDefaultCredentials = true;
        //client.Credentials = CredentialCache.DefaultNetworkCredentials;
        static void Main(string[] args)
        {
         
           //DefaultSendEmail();
           // WriteEmail();
            Console.WriteLine(WriteEmail().ToString());
            //CreateMessageWithAttachment();
        }
      
        //Single receiver test.MSDN上最简单的发送邮件
        public static void DefaultSendEmail(string server)//你的邮件服务器
        {
            string to = "[email protected]";
            string from = "[email protected]";
            string subject = "Using the new SMTP client.";
            string body = @"Using this new feature, you can send an e-mail message from an application very easily.";
            MailMessage message = new MailMessage(from, to, subject, body);
           
            SmtpClient client = new SmtpClient(server);
            //Console.WriteLine("Changing time out from {0} to 100.", client.Timeout);
            //client.Timeout = 100;
            // Credentials are necessary if the server requires the client
            // to authenticate before it will send e-mail on the client's behalf.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;
            client.Send(message);
            Console.WriteLine("Email sended.");
        }

        //Multiply users test.
        public static string MultiSendEmail(string mailFrom,string mailTo,string mailCC,string mailHead,string mailBody,ArrayList mailAttach,bool isHtml)
        {
            //改用XML文件在Web.Configure中配置.
            string eServer = "***.**.**.**";//需要换成你的邮件服务器
            int ePort = 25;//默认
            MailMessage eMail = new MailMessage();
            SmtpClient eClient = new SmtpClient(eServer,ePort);
            eClient.UseDefaultCredentials = true;

            eMail.Subject = mailHead;
            eMail.SubjectEncoding = Encoding.UTF8;
           
            eMail.Body = mailBody;
            eMail.BodyEncoding = Encoding.UTF8;

            eMail.From = new MailAddress(mailFrom);
            //Receiver
            string[] arrMailAddr;
            try
            {
               
                //用";"分割多个收件人.