萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> .net編程 >> C#控制台程序,發送郵件,可帶附件的代碼!

C#控制台程序,發送郵件,可帶附件的代碼!

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
            {
               
                //用";"分割多個收件人.

copyright © 萬盛學電腦網 all rights reserved