目次

添付ファイルをつけたメールをプログラムから送信する

目次

プログラムから添付ファイルつきのメールを送信するコード例です。

概要

添付ファイルを送信する場合には、MailMessageクラスのAttachementsにAddメソッドでAttachmentクラスを追加することで、ファイルを添付できます。

下図のコードでは、画像ファイル"sample.jpg"のファイル名をAttamentクラスのコンストラクタに指定しAttachmentクラスのインスタンスattachmentを作成し、MailMessageクラスのAttachmentsにAddメソッドで追加してファイルを添付しています。

コード例

//MailMessageの作成
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
//送信者の設定
msg.From = new System.Net.Mail.MailAddress("auto@automail.ipentec.com", "自動送信メール");
//宛先の設定
msg.To.Add(new System.Net.Mail.MailAddress("ipentec-manager@gmail.com", "iPentec Manager"));
//件名
msg.Subject = "自動送信メール";
//本文
msg.Body = "このメッセージは自動送信によるメールです。";

//添付ファイル (画像)
string jpgname ="sample.jpg";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(jpgname);
//attachment = new System.Net.Mail.Attachment(datapath+jpgname);//添付ファイルのパスを指定する

attachment.ContentType = new System.Net.Mime.ContentType("image/jpeg");
//Attachmentsに追加する
msg.Attachments.Add(attachment);

System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
//SMTPサーバーを指定する
sc.Host = Properties.Settings.Default.SMTPServer; // or "mailgate.ipentec.com"; 
sc.Port = Properties.Settings.Default.SMTPPort;   // or 587;

//ユーザー名とパスワードを設定する
sc.Credentials = new System.Net.NetworkCredential(
Properties.Settings.Default.SMTPAuthUser, Properties.Settings.Default.SMTPAuthPass);
//sc.Credentials = new System.Net.NetworkCredential("automail","pass123456"); 

//現在は、EnableSslがtrueでは失敗する
sc.EnableSsl = false;

//メッセージを送信する
sc.Send(msg);

//後始末
msg.Dispose();

AuthorPortraitAlt
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2009-12-11
Copyright © 1995–2025 iPentec all rights reserverd.