asp.net C#使用SMTP發送附件程式

來源:互聯網
上載者:User

幾年前有股學C#的熱情,寫下了C#發送郵件和C#發送帶附件的郵件文章,放到baidu上。之前有有放到ttlsa上,但是搜尋發現文章貌似被刪除了,今天特意重新補充一下。此文留作記錄.

以下代碼除了實現發送簡單的郵件以外,還包括了發送附件。From圖沒有貼出,上面就兩按鈕,一個“添加附件”、一個“發送”。點擊添加附件選擇檔案, 檔案路徑全儲存在listbox1中。在發送按鈕方法中,把listbox1所有的檔案添加到mailmessage對象裡作為郵件發送出去了,請看代碼

 代碼如下 複製代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Net.Mime;

namespace SmtpTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
try
{
//定義一個mail對象
MailMessage mailmessage = new MailMessage(““, ““, “this is a test”, “yes!test!”);
//from email,to email,主題,郵件內容
mailmessage.Priority = MailPriority.Normal; //郵件優先順序
SmtpClient smtpClient = new SmtpClient(“smtp.163.com”, 25); //smtp地址以及連接埠號碼
smtpClient.Credentials = new NetworkCredential(“ttlsa.com”, “xxxxxx”);//smtp使用者名稱密碼
smtpClient.EnableSsl = true; //啟用ssl

//添加附件
Attachment attachment =null;
if(listBox1.Items.Count>0)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
string pathFileName = listBox1.Items[i].ToString();
string extName = Path.GetExtension(pathFileName).ToLower(); //擷取副檔名
if(extName==”.rar”||extName==”.zip”) //.rar和.zip的檔案屬於壓縮檔類型
{
attachment = new Attachment(pathFileName,MediaTypeNames.Application.Zip);

}else
{
attachment = new Attachment(pathFileName,MediaTypeNames.Application.Octet);
}
//設定附件的MIME資訊
ContentDisposition cd = attachment.ContentDisposition;
cd.CreationDate = File.GetCreationTime(pathFileName);//設定附件的建立時間
cd.ModificationDate = File.GetLastWriteTime(pathFileName);//設定附件的修改時間
cd.ReadDate = File.GetLastAccessTime(pathFileName);//設定附件的訪問時間
mailmessage.Attachments.Add(attachment);//將附件添加到mailmessage對象
}
}
smtpClient.Send(mailmessage);
MessageBox.Show(“發送成功”);
}
catch (SmtpException se)
{
MessageBox.Show(se.StatusCode.ToString());
}
}

//添加附件,把檔案添加到listbox中
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog opd = new OpenFileDialog();//定義一個選擇檔案的對話方塊
opd.Multiselect = true;//允許選擇多個檔案
opd.CheckFileExists = true;//檢查檔案是否存在
opd.ValidateNames = true;//檢查檔案名稱的可用性
opd.ShowDialog();//開啟對話方塊
if(opd.FileNames.Length>0)//將選擇的檔案路徑寫入listbox中
{
listBox1.Items.AddRange(opd.FileNames);
}
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.