コード例 #1
0
        public static void Mail(string id, string pass, string from, string to, string subject, string body, string path)
        {
            //Console.WriteLine("Hello SMTP World!");

            /*
             * string id = "<gmailのログインID>";
             * string pass = "******";
             * string from = "<宛先>";
             * string to = "<自分のメール>";
             * string subject = "送信テスト : " + DateTime.Now.ToString();
             * string body = "from t.masuda";
             */
#if false
            var smtp = new System.Net.Mail.SmtpClient();
            smtp.Host        = "smtp.gmail.com";                           //SMTPサーバ
            smtp.Port        = 587;                                        //SMTPポート
            smtp.EnableSsl   = true;
            smtp.Credentials = new System.Net.NetworkCredential(id, pass); //認証
            var msg = new System.Net.Mail.MailMessage(from, to, subject, body);
            smtp.Send(msg);                                                //メール送信
#else
            var smtp = new MailKit.Net.Smtp.SmtpClient();
            smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
            smtp.Authenticate(id, pass);

            var mail    = new MimeKit.MimeMessage();
            var builder = new MimeKit.BodyBuilder();

            mail.From.Add(new MimeKit.MailboxAddress("", from));
            mail.To.Add(new MimeKit.MailboxAddress("", to));
            mail.Subject     = subject;
            builder.TextBody = body;
            //mail.Body = builder.ToMessageBody();

            //var path = @"C:\Windows\Web\Wallpaper\Theme2\img10.jpg"; // 添付したいファイル
            var attachment = new MimeKit.MimePart("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                Content                 = new MimeKit.MimeContent(File.OpenRead(path)),
                ContentDisposition      = new MimeKit.ContentDisposition(),
                ContentTransferEncoding = MimeKit.ContentEncoding.Base64,
                FileName                = System.IO.Path.GetFileName(path)
            };

            var multipart = new MimeKit.Multipart("mixed");
            multipart.Add(builder.ToMessageBody());
            multipart.Add(attachment);

            mail.Body = multipart;

            smtp.Send(mail);
            smtp.Disconnect(true);
#endif

            Console.WriteLine("メールを送信しました");
        }
コード例 #2
0
 private async Task SendHtmlMail(string smtpserver, int port, bool usessh, string account, string pwd, string FromNickName, string FromAccount, string ToNickName, string ToAccount, string Subject, string HtmlContent)
 {
     try
     {
         var message = new MimeKit.MimeMessage();
         message.From.Add(new MimeKit.MailboxAddress(FromNickName, FromAccount));
         message.To.Add(new MimeKit.MailboxAddress(ToNickName, ToAccount));
         message.Subject = Subject;
         var html = new MimeKit.TextPart("html")
         {
             Text = HtmlContent
         };
         // create an image attachment for the file located at path
         var alternative = new MimeKit.Multipart("alternative");
         alternative.Add(html);
         // now create the multipart/mixed container to hold the message text and the
         // image attachment
         var multipart = new MimeKit.Multipart("mixed");
         multipart.Add(alternative);
         message.Body = multipart;
         using (var client = new MailKit.Net.Smtp.SmtpClient())
         {
             client.Connect(smtpserver, port, usessh);
             // Note: since we don't have an OAuth2 token, disable
             // the XOAUTH2 authentication mechanism.
             client.AuthenticationMechanisms.Remove("XOAUTH2");
             // Note: only needed if the SMTP server requires authentication
             var mailFromAccount = account;
             var mailPassword    = pwd;
             client.Authenticate(mailFromAccount, mailPassword);
             client.Send(message);
             client.Disconnect(true);
         }
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException(ex.Message);
     }
 }
コード例 #3
0
        // https://stackoverflow.com/questions/24170852/strip-attachments-from-emails-using-mailkit-mimekit
        static void SaveAttachments()
        {
            MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.Load(@"x:\sample.eml");

            System.Collections.Generic.List <MimeKit.MimeEntity> attachments =
                System.Linq.Enumerable.ToList(mimeMessage.Attachments);

            if (System.Linq.Enumerable.Any(attachments))
            {
                // Only multipart mails can have attachments
                MimeKit.Multipart multipart = mimeMessage.Body as MimeKit.Multipart;
                if (multipart != null)
                {
                    foreach (MimeKit.MimeEntity attachment in mimeMessage.Attachments)
                    {
                        multipart.Remove(attachment);
                    } // Next attachment
                }     // End if (multipart != null)

                mimeMessage.Body = multipart;
            } // End if(System.Linq.Enumerable.Any(attachments))

            mimeMessage.WriteTo(new System.IO.FileStream(@"x:\stripped.eml", System.IO.FileMode.CreateNew));
        } // End Sub SaveAttachments
コード例 #4
0
        /// <summary>
        /// メール送信を実行します。
        /// </summary>
        /// <param name="fromUser"></param>
        /// <param name="fromAddress"></param>
        /// <param name="toUser"></param>
        /// <param name="toAddress"></param>
        /// <param name="title"></param>
        /// <param name="msg"></param>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="attachList"></param>
        public static void Send(string fromUser, string fromAddress, string toUser, string toAddress, string title, string msg, string host, int port, string userName, string password, Dictionary <int, string> attachList)
        {
            try
            {
                List <string> tmpAttachPathList = new List <string>();
                List <Stream> attachStreamList  = new List <Stream>();
                var           message           = new MimeKit.MimeMessage();

                string[] name      = toUser.Replace(",", ";").Split(';');
                string[] addresses = toAddress.Replace(",", ";").Split(';');

                message.From.Add(new MimeKit.MailboxAddress(fromUser, fromAddress));

                try
                {
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        message.To.Add(new MimeKit.MailboxAddress(name[i].Trim(), addresses[i].Trim()));
                    }
                }
                catch (Exception)
                {
                    throw new Exception("送信先名・送信先アドレスの数が一致しません。");
                }

                message.Subject = title;
                var textPart = new MimeKit.TextPart(MimeKit.Text.TextFormat.Plain);
                textPart.Text = msg;

                if (HasAttach(attachList))
                {
                    var multipart = new MimeKit.Multipart("mixed");
                    multipart.Add(textPart);
                    foreach (var attach in attachList)
                    {
                        if (!string.IsNullOrEmpty(attach.Value))
                        {
                            if (!System.IO.File.Exists(attach.Value))
                            {
                                throw new Exception("添付ファイル : [" + attach.Value + "] が見つかりませんでした。");
                            }
                            var attachment = new MimeKit.MimePart();
                            attachment.Content = new MimeKit.MimeContent(System.IO.File.OpenRead(attach.Value));
                            attachStreamList.Add(attachment.Content.Stream);
                            attachment.ContentDisposition      = new MimeKit.ContentDisposition();
                            attachment.ContentTransferEncoding = MimeKit.ContentEncoding.Base64;
                            attachment.FileName = System.IO.Path.GetFileName(attach.Value);
                            multipart.Add(attachment);
                        }
                    }
                    message.Body = multipart;
                }
                else
                {
                    message.Body = textPart;
                }
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    client.Connect(host, port);
                    if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                    {
                        client.Authenticate(userName, password);
                    }
                    client.Send(message);
                    client.Disconnect(true);
                }
                //メール添付ファイルのストリームを閉じる
                foreach (var s in attachStreamList)
                {
                    s.Close();
                }
            }
            catch (Exception ex)
            {
                throw Program.ThrowException(ex);
            }
        }