宇宙仮面の C# プログラミング
   

Top

C# 2005

C# 2003

C# Windows Mobile

SQL Server 2005

SQL Server 2000

Virtual PC/Server

C# 研究室ブログ

C# ソフトウェア ダウンロード

C# 開発環境

宇宙仮面の C# プログラミングについて

.NET/C# eGroup JP

INETA Japan



Google
Web
uchukamen.com









Send Mail (メールの送信)

開発環境: Visual Studio 2005 

1.目次

1.目次
2.目的
3.参考書
4.普通のSMTPサーバーにメールを送信する場合
5.POP Before SMTPのメールサーバーに送信する場合
6.テスト用ソースコード

2.目的

テスト用に作ってみました。
とりあえずメモっておきます。


3.参考書

(1) System.Web.Mail 名前空間
(2) パスワードの暗号化はこちら

4.普通のSMTPサーバーにメールを送信する場合


普通のSMTP サーバーに送信する場合は、次のようになります。

普通のメール送信パターン
....
using System.IO;
using System.Text;
using System.Web;
using System.Net;
....

MailMessage mailMessage = new MailMessage();
mailMessage.From = "送信者メールアドレスを入れる";
mailMessage.To = "Toメールアドレスを入れる";
mailMessage.Cc = "Ccメールアドレスを入れる";
mailMessage.Bcc = "Bccメールアドレスを入れる";
mailMessage.Subject = "件名を入れる";

// Encoding は、デフォルトで iso-2022-jp になっているので、
// 指定する必要は無い。
mailMessage.BodyEncoding = Encoding.GetEncoding("iso-2022-jp");
mailMessage.Body = "本文を入れる";

// 重要度の指定 (Low, Normal, Highから選ぶ)
// 指定する必要は無い。
mailMessage.Priority = MailPriority.Low;
// メールの添付ファイル
// 添付ファイルのエンコーディングは、Base64とUUEncodeがサポートされている。
MailAttachment attach1 = new MailAttachment(ファイル名, MailEncoding.Base64);

MailAttachment attach1 = new MailAttachment(item.SubItems[1].Text);
mailMessage.Attachments.Add(attach1);

SmtpMail.SmtpServer = "SMTP サーバーを入れる";
SmtpMail.Send(mailMessage);

 

例外が発生した場合のチェックポイント
System.Web.HttpException
『'CDO.Message' オブジェクトにアクセスできませんでした。』

の例外があがる場合は、次の点を確認してみてください。

  • To, From などのメールアドレスが正しくセットされていない。
  • POP Before STMPなどの特別な認証を必要なサーバかどうか。

// なんちゅうエラーメッセージなんだ〜〜!
// ちなみに、CDOとは Collaboration Data Objects と呼ばれるメッセージング・コンポーネントです。 Windows 2000/XP/Server 2003で、標準装備している。

 

メールが文字化けする場合のチェックポイント
メールのエンコーディングは、ISO 2022-JP が推奨されています。携帯電話でのメールを受信する場合やいくつかのメールソフトでは、ISO 2022-JPフォーマットでないと文字化けするものがあります。

デフォルトでISO 2022-JPで送信してくれているようなので、普通は大丈夫だと思いますが、メールのサブジェクト、およびボディのエンコーディングが、ISO 2022-JPかどうか、確認してみてください。

    

5.POP Before SMTPのメールサーバーに送信する場合

POP Before SMTP とは、メールを送信する際のユーザ認証方法の1つです。もともとSMTPは、ユーザ認証無しにメールを送信することができてしまうため、スパムメールなどを送りつけられてしまうので、メールを送信する直前にPOPサーバにログインしてからでないと、メールを送信できないとするものです。

Yahoo メールでは POP Before SMTP で、ユーザ認証を行っています。

POP Before SMTP サーバの場合のメール送信パターン
....
using System.IO;
using System.Text;
using System.Web;
using System.Net;
....

/// POP Before SMTP サーバの場合は、一度POPサーバにログインする必要がある。
string userName = "ユーザ名を入れる";
string password = "パスワードを入れる";
TcpClient tcp = new TcpClient();
tcp.Connect("POPサーバ名を入れる",110);
using (StreamWriter sw = new StreamWriter(tcp.GetStream()))
sw.Write("USER " + userName + "\nPASS " + password + "\nQUIT\n"); 
tcp.Close();
MailMessage mailMessage = new MailMessage();
mailMessage.From = "送信者メールアドレスを入れる";
mailMessage.To = "Toメールアドレスを入れる";
mailMessage.Cc = "Ccメールアドレスを入れる";
mailMessage.Bcc = "Bccメールアドレスを入れる";
mailMessage.Subject = "件名を入れる";

// Encoding は、デフォルトで iso-2022-jp になっているので、
// 指定する必要は無い。
mailMessage.BodyEncoding = Encoding.GetEncoding("iso-2022-jp");
mailMessage.Body = "本文を入れる";

// 重要度の指定 (Low, Mid, Highから選ぶ)
// 指定する必要な無い。
mailMessage.Priority = MailPriority.Low;
// メールの添付ファイル
// 添付ファイルのエンコーディングは、Base64とUUEncodeがサポートされている。
MailAttachment attach1 = new MailAttachment(ファイル名, MailEncoding.Base64);

MailAttachment attach1 = new MailAttachment(item.SubItems[1].Text);
mailMessage.Attachments.Add(attach1);

SmtpMail.SmtpServer = "SMTP サーバーを入れる";
SmtpMail.Send(mailMessage);

 

ユーザ名、パスワードの取り扱いに注意
ユーザ名、パスワードを毎回これらのデータを入力するのは大変なので、どこかにストアしておくことになりますが、それらの扱いは十分注意する必要があります。

パスワードの暗号化には、参考文献(2)が使えるでしょう。

 

6.テスト用ソースコード

 

変更履歴
2005/2/16password の区切りを追加
2004/10/24初版作成 V1.0
 
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Web.Mail;
using System.Net.Sockets;
using System.IO;

namespace SendMail
{
	/// 
	/// Form1 の概要の説明です。
	/// 
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button buttonSend;
		private System.Windows.Forms.RichTextBox richTextBoxBody;
		private System.Windows.Forms.TextBox textBoxSubject;
		private System.Windows.Forms.Label labelTo;
		private System.Windows.Forms.Label labelSubject;
		private System.Windows.Forms.Label labelCc;
		private System.Windows.Forms.ColumnHeader columnHeader1;
		private System.Windows.Forms.ColumnHeader columnHeader2;
		private System.Windows.Forms.Button buttonAttach;
		private System.Windows.Forms.OpenFileDialog openFileDialog1;
		private System.Windows.Forms.ListView listViewAttachment;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox textBoxPop3Server;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox textBoxSmtpServer;
		private System.Windows.Forms.TextBox textBoxUserName;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.TextBox textBoxTo;
		private System.Windows.Forms.TextBox textBoxPassword;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.TextBox textBoxCc;
		private System.Windows.Forms.TextBox textBoxBcc;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.TextBox textBoxFrom;
		private System.Windows.Forms.Label label7;
		private System.Windows.Forms.CheckBox checkBoxPopBeforeSMTP;
		/// 
		/// 必要なデザイナ変数です。
		/// 
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Windows フォーム デザイナ サポートに必要です。
			//
			InitializeComponent();

			//
			// TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。
			//
		}

		/// 
		/// 使用されているリソースに後処理を実行します。
		/// 
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows フォーム デザイナで生成されたコード 
		/// 
		/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
		/// コード エディタで変更しないでください。
		/// 
		private void InitializeComponent()
		{
			this.buttonSend = new System.Windows.Forms.Button();
			this.richTextBoxBody = new System.Windows.Forms.RichTextBox();
			this.textBoxSubject = new System.Windows.Forms.TextBox();
			this.labelTo = new System.Windows.Forms.Label();
			this.labelSubject = new System.Windows.Forms.Label();
			this.labelCc = new System.Windows.Forms.Label();
			this.buttonAttach = new System.Windows.Forms.Button();
			this.listViewAttachment = new System.Windows.Forms.ListView();
			this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
			this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
			this.label1 = new System.Windows.Forms.Label();
			this.textBoxPop3Server = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.textBoxSmtpServer = new System.Windows.Forms.TextBox();
			this.textBoxUserName = new System.Windows.Forms.TextBox();
			this.label4 = new System.Windows.Forms.Label();
			this.textBoxTo = new System.Windows.Forms.TextBox();
			this.textBoxPassword = new System.Windows.Forms.TextBox();
			this.label5 = new System.Windows.Forms.Label();
			this.textBoxCc = new System.Windows.Forms.TextBox();
			this.textBoxBcc = new System.Windows.Forms.TextBox();
			this.label6 = new System.Windows.Forms.Label();
			this.textBoxFrom = new System.Windows.Forms.TextBox();
			this.label7 = new System.Windows.Forms.Label();
			this.checkBoxPopBeforeSMTP = new System.Windows.Forms.CheckBox();
			this.SuspendLayout();
			// 
			// buttonSend
			// 
			this.buttonSend.Location = new System.Drawing.Point(344, 472);
			this.buttonSend.Name = "buttonSend";
			this.buttonSend.Size = new System.Drawing.Size(80, 32);
			this.buttonSend.TabIndex = 23;
			this.buttonSend.Text = "Send";
			this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);
			// 
			// richTextBoxBody
			// 
			this.richTextBoxBody.Location = new System.Drawing.Point(48, 272);
			this.richTextBoxBody.Name = "richTextBoxBody";
			this.richTextBoxBody.Size = new System.Drawing.Size(376, 96);
			this.richTextBoxBody.TabIndex = 19;
			this.richTextBoxBody.Text = "abcテスト漢字";
			// 
			// textBoxSubject
			// 
			this.textBoxSubject.Location = new System.Drawing.Point(104, 240);
			this.textBoxSubject.Name = "textBoxSubject";
			this.textBoxSubject.Size = new System.Drawing.Size(320, 19);
			this.textBoxSubject.TabIndex = 17;
			this.textBoxSubject.Text = "abcテスト漢字";
			// 
			// labelTo
			// 
			this.labelTo.Location = new System.Drawing.Point(72, 152);
			this.labelTo.Name = "labelTo";
			this.labelTo.Size = new System.Drawing.Size(24, 16);
			this.labelTo.TabIndex = 10;
			this.labelTo.Text = "To:";
			// 
			// labelSubject
			// 
			this.labelSubject.Location = new System.Drawing.Point(48, 240);
			this.labelSubject.Name = "labelSubject";
			this.labelSubject.Size = new System.Drawing.Size(48, 16);
			this.labelSubject.TabIndex = 16;
			this.labelSubject.Text = "Subject:";
			// 
			// labelCc
			// 
			this.labelCc.Location = new System.Drawing.Point(72, 184);
			this.labelCc.Name = "labelCc";
			this.labelCc.Size = new System.Drawing.Size(24, 16);
			this.labelCc.TabIndex = 12;
			this.labelCc.Text = "Cc:";
			// 
			// buttonAttach
			// 
			this.buttonAttach.Location = new System.Drawing.Point(240, 472);
			this.buttonAttach.Name = "buttonAttach";
			this.buttonAttach.Size = new System.Drawing.Size(88, 32);
			this.buttonAttach.TabIndex = 22;
			this.buttonAttach.Text = "Attachments";
			this.buttonAttach.Click += new System.EventHandler(this.buttonAttach_Click);
			// 
			// listViewAttachment
			// 
			this.listViewAttachment.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																								 this.columnHeader1,
																								 this.columnHeader2});
			this.listViewAttachment.Location = new System.Drawing.Point(48, 384);
			this.listViewAttachment.Name = "listViewAttachment";
			this.listViewAttachment.Size = new System.Drawing.Size(376, 80);
			this.listViewAttachment.TabIndex = 20;
			this.listViewAttachment.View = System.Windows.Forms.View.Details;
			this.listViewAttachment.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listView1_KeyDown);
			// 
			// columnHeader1
			// 
			this.columnHeader1.Text = "File Name";
			this.columnHeader1.Width = 154;
			// 
			// columnHeader2
			// 
			this.columnHeader2.Text = "Full File Name";
			this.columnHeader2.Width = 224;
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(72, 216);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(32, 16);
			this.label1.TabIndex = 14;
			this.label1.Text = "Bcc:";
			// 
			// textBoxPop3Server
			// 
			this.textBoxPop3Server.Location = new System.Drawing.Point(104, 16);
			this.textBoxPop3Server.Name = "textBoxPop3Server";
			this.textBoxPop3Server.Size = new System.Drawing.Size(320, 19);
			this.textBoxPop3Server.TabIndex = 1;
			this.textBoxPop3Server.Text = "";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(16, 16);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(80, 16);
			this.label2.TabIndex = 0;
			this.label2.Text = "POP3 Server";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(16, 48);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(88, 16);
			this.label3.TabIndex = 2;
			this.label3.Text = "SMTP Server";
			// 
			// textBoxSmtpServer
			// 
			this.textBoxSmtpServer.Location = new System.Drawing.Point(104, 48);
			this.textBoxSmtpServer.Name = "textBoxSmtpServer";
			this.textBoxSmtpServer.Size = new System.Drawing.Size(320, 19);
			this.textBoxSmtpServer.TabIndex = 3;
			this.textBoxSmtpServer.Text = "";
			// 
			// textBoxUserName
			// 
			this.textBoxUserName.Location = new System.Drawing.Point(104, 80);
			this.textBoxUserName.Name = "textBoxUserName";
			this.textBoxUserName.Size = new System.Drawing.Size(120, 19);
			this.textBoxUserName.TabIndex = 5;
			this.textBoxUserName.Text = "";
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(24, 80);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(72, 16);
			this.label4.TabIndex = 4;
			this.label4.Text = "User Name";
			// 
			// textBoxTo
			// 
			this.textBoxTo.Location = new System.Drawing.Point(104, 144);
			this.textBoxTo.Name = "textBoxTo";
			this.textBoxTo.Size = new System.Drawing.Size(320, 19);
			this.textBoxTo.TabIndex = 11;
			this.textBoxTo.Text = "";
			// 
			// textBoxPassword
			// 
			this.textBoxPassword.Location = new System.Drawing.Point(304, 80);
			this.textBoxPassword.Name = "textBoxPassword";
			this.textBoxPassword.PasswordChar = '*';
			this.textBoxPassword.Size = new System.Drawing.Size(120, 19);
			this.textBoxPassword.TabIndex = 7;
			this.textBoxPassword.Text = "";
			// 
			// label5
			// 
			this.label5.Location = new System.Drawing.Point(240, 80);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(56, 16);
			this.label5.TabIndex = 6;
			this.label5.Text = "Password";
			// 
			// textBoxCc
			// 
			this.textBoxCc.Location = new System.Drawing.Point(104, 176);
			this.textBoxCc.Name = "textBoxCc";
			this.textBoxCc.Size = new System.Drawing.Size(320, 19);
			this.textBoxCc.TabIndex = 13;
			this.textBoxCc.Text = "";
			// 
			// textBoxBcc
			// 
			this.textBoxBcc.Location = new System.Drawing.Point(104, 208);
			this.textBoxBcc.Name = "textBoxBcc";
			this.textBoxBcc.Size = new System.Drawing.Size(320, 19);
			this.textBoxBcc.TabIndex = 15;
			this.textBoxBcc.Text = "";
			// 
			// label6
			// 
			this.label6.Location = new System.Drawing.Point(8, 288);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(40, 16);
			this.label6.TabIndex = 18;
			this.label6.Text = "Body";
			// 
			// textBoxFrom
			// 
			this.textBoxFrom.Location = new System.Drawing.Point(104, 112);
			this.textBoxFrom.Name = "textBoxFrom";
			this.textBoxFrom.Size = new System.Drawing.Size(320, 19);
			this.textBoxFrom.TabIndex = 9;
			this.textBoxFrom.Text = "";
			// 
			// label7
			// 
			this.label7.Location = new System.Drawing.Point(64, 120);
			this.label7.Name = "label7";
			this.label7.Size = new System.Drawing.Size(40, 16);
			this.label7.TabIndex = 8;
			this.label7.Text = "From";
			// 
			// checkBoxPopBeforeSMTP
			// 
			this.checkBoxPopBeforeSMTP.Checked = true;
			this.checkBoxPopBeforeSMTP.CheckState = System.Windows.Forms.CheckState.Checked;
			this.checkBoxPopBeforeSMTP.Location = new System.Drawing.Point(56, 472);
			this.checkBoxPopBeforeSMTP.Name = "checkBoxPopBeforeSMTP";
			this.checkBoxPopBeforeSMTP.Size = new System.Drawing.Size(152, 24);
			this.checkBoxPopBeforeSMTP.TabIndex = 21;
			this.checkBoxPopBeforeSMTP.Text = "Pop Before SMTP";
			this.checkBoxPopBeforeSMTP.CheckedChanged += new System.EventHandler(this.checkBoxPopBeforeSMTP_CheckedChanged);
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 12);
			this.ClientSize = new System.Drawing.Size(440, 510);
			this.Controls.Add(this.checkBoxPopBeforeSMTP);
			this.Controls.Add(this.label7);
			this.Controls.Add(this.textBoxFrom);
			this.Controls.Add(this.label6);
			this.Controls.Add(this.textBoxBcc);
			this.Controls.Add(this.textBoxCc);
			this.Controls.Add(this.label5);
			this.Controls.Add(this.textBoxPassword);
			this.Controls.Add(this.textBoxTo);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.textBoxUserName);
			this.Controls.Add(this.textBoxSmtpServer);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.textBoxPop3Server);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.listViewAttachment);
			this.Controls.Add(this.buttonAttach);
			this.Controls.Add(this.labelCc);
			this.Controls.Add(this.labelSubject);
			this.Controls.Add(this.labelTo);
			this.Controls.Add(this.textBoxSubject);
			this.Controls.Add(this.richTextBoxBody);
			this.Controls.Add(this.buttonSend);
			this.Name = "Form1";
			this.Text = "Send Mail";
			this.ResumeLayout(false);

		}
		#endregion

		/// 
		/// アプリケーションのメイン エントリ ポイントです。
		/// 
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void buttonSend_Click(object sender, System.EventArgs e)
		{
			try
			{
				this.Cursor = Cursors.WaitCursor;

				// POP before SMTP が必要な場合
				if (this.checkBoxPopBeforeSMTP.Checked)
					PopBeforeSMTP();

				SendMail();	
			}
			catch (Exception exc)
			{
				MessageBox.Show(exc.Message, 
					Application.ProductName, 
					MessageBoxButtons.OK, 
					MessageBoxIcon.Error);
			}
			finally
			{

				this.Cursor = Cursors.Default;
			}
		}

		private void buttonAttach_Click(object sender, System.EventArgs e)
		{
			DialogResult res = this.openFileDialog1.ShowDialog();
			if(res == DialogResult.OK)
			{
				string fileName = openFileDialog1.FileName;
				FileInfo fileInfo = new FileInfo(fileName);
				ListViewItem item = this.listViewAttachment.Items.Add(fileInfo.Name);
				item.SubItems.Add(fileInfo.FullName);
			}
		}

		private void PopBeforeSMTP()
		{
			string userName = this.textBoxUserName.Text;
			string password = this.textBoxPassword.Text;
			TcpClient tcp = new TcpClient();
			tcp.Connect(this.textBoxPop3Server.Text,110);
			using (StreamWriter sw = new StreamWriter(tcp.GetStream()))
				sw.Write("USER " + userName + "\nPASS " + password + "\nQUIT\n"); 
			tcp.Close();
		}

		private void SendMail()
		{
			// MailMessageを作成する。
			MailMessage mailMessage = new MailMessage();
			mailMessage.From = this.textBoxFrom.Text;
			mailMessage.To = this.textBoxTo.Text;
			mailMessage.Cc = this.textBoxCc.Text;
			mailMessage.Bcc = this.textBoxBcc.Text;
			mailMessage.Subject = this.textBoxSubject.Text;
			mailMessage.BodyEncoding = Encoding.GetEncoding("iso-2022-jp");
			mailMessage.Body = this.richTextBoxBody.Text;
			mailMessage.Priority = MailPriority.Normal;

			// 添付ファイルを追加する。
			foreach(ListViewItem item in this.listViewAttachment.Items)
			{
				MailAttachment attach1 = new MailAttachment(item.SubItems[1].Text);
				mailMessage.Attachments.Add(attach1);
			}

			// MailMessageを送信する。
			SmtpMail.SmtpServer = this.textBoxSmtpServer.Text;
			SmtpMail.Send(mailMessage);
		}

		// ListView でアタッチメントを選択した状態でDELを押して削除する処理
		private void listView1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Delete)
				DeleteSelectedItem();
		}

		private void DeleteSelectedItem()
		{
			if (listViewAttachment.SelectedItems.Count > 0)
				listViewAttachment.SelectedItems[0].Remove();
		}

		private void checkBoxPopBeforeSMTP_CheckedChanged(object sender, System.EventArgs e)
		{
			bool popBeforeSmtp = this.checkBoxPopBeforeSMTP.Checked;
			textBoxPop3Server.Enabled = popBeforeSmtp;			
			this.textBoxUserName.Enabled = popBeforeSmtp;
			this.textBoxPassword.Enabled = popBeforeSmtp;
		}
	}
}
このページを評価する

このページを評価する

悪い             良い
1 2 3 4 5
コメント(一言お願いします)