Exemplo n.º 1
0
		public void TestArgumentExceptions ()
		{
			var multipart = new Multipart ();

			Assert.Throws<ArgumentNullException> (() => new Multipart ((MimeEntityConstructorArgs) null));
			Assert.Throws<ArgumentNullException> (() => new Multipart ((string) null));
			Assert.Throws<ArgumentNullException> (() => new Multipart ("mixed", null));
			Assert.Throws<ArgumentException> (() => new Multipart ("mixed", 5));

			Assert.Throws<ArgumentNullException> (() => multipart.Boundary = null);

			Assert.Throws<ArgumentNullException> (() => multipart.Add (null));
			Assert.Throws<ArgumentOutOfRangeException> (() => multipart.Insert (-1, new TextPart ("plain")));
			Assert.Throws<ArgumentNullException> (() => multipart.Insert (0, null));
			Assert.Throws<ArgumentNullException> (() => multipart.Remove (null));
			Assert.Throws<ArgumentOutOfRangeException> (() => multipart.RemoveAt (-1));

			Assert.Throws<ArgumentNullException> (() => multipart.Contains (null));
			Assert.Throws<ArgumentNullException> (() => multipart.IndexOf (null));

			Assert.Throws<ArgumentOutOfRangeException> (() => multipart[0] = new TextPart ("plain"));
			Assert.Throws<ArgumentNullException> (() => multipart[0] = null);

			Assert.Throws<ArgumentNullException> (() => multipart.Accept (null));

			Assert.Throws<ArgumentOutOfRangeException> (() => multipart.CopyTo (new MimeEntity[0], -1));
			Assert.Throws<ArgumentNullException> (() => multipart.CopyTo (null, 0));

			Assert.Throws<ArgumentOutOfRangeException> (() => multipart.Prepare (EncodingConstraint.SevenBit, 1));
		}
Exemplo n.º 2
0
 public static Multipart AddTextPart(this Multipart part, string message)
 {
     part.Add(new TextPart("plain")
     {
         Text = message
     });
     return(part);
 }
Exemplo n.º 3
0
        public static MimeMessage MultipartMimeMessage(byte[] dataSource) // throws MessagingException
        {
            Multipart   mimeMultipart = MimeEntity.Load(ParserOptions.Default, dataSource.ToStream(), false) as Multipart;
            MimeMessage m             = new MimeMessage();

            m.Body = mimeMultipart;
            return(m);
        }
Exemplo n.º 4
0
 public static Multipart AttachFiles(this Multipart part, IEnumerable <IFile> files)
 {
     foreach (var file in files)
     {
         part.Add(Create(file));
     }
     return(part);
 }
        /// <summary>
        /// Diese Methode wird aufgerufen, wenn eine Schulung angelegt wurde und generiert und schickt eine Mail an den Dozenten der Schulung.
        /// </summary>
        /// <param name="schulung">Die Schulung, die angelegt wurde</param>
        public async Task GenerateAndSendAnlegeMailAsync(Schulung schulung, string rootUrl, string vorstand)
        {
            try
            {
                MimeMessage message = new MimeMessage();
                message.From.Add(new MailboxAddress("Schulungsportal", emailSender.GetAbsendeAdresse())); //Absender
                foreach (var dozent in schulung.Dozenten)
                {
                    message.To.Add(GetSafeMailboxAddress(dozent.Name, dozent.EMail)); // Empfaenger
                }
                message.Subject = "[INFO/noreply] Schulung angelegt";                 //Betreff

                var teilnehmerListeUrl = rootUrl + "/Schulung/Teilnehmer/" + schulung.AccessToken;

                var dozentenEmails = schulung.Dozenten.Select(d => d.EMail);
                var attachments    = GetAppointment(schulung, dozentenEmails, emailSender.GetAbsendeAdresse(), istAbsage: false);

                MailViewModel mvm = new MailViewModel
                {
                    //CCLogoFile = "cclogo.png@"+Guid.NewGuid().ToString(),
                    //FacebookLogoFile = "fblogo.png@" + Guid.NewGuid().ToString(),
                    //InstaLogoFile = "instalogo.png@" + Guid.NewGuid().ToString(),
                    Schulung           = schulung,
                    Vorstand           = vorstand,
                    TeilnehmerListeUrl = teilnehmerListeUrl,
                };

                var body = new TextPart("html") //Inhalt
                {
                    Text = await RunCompileAsync("AnlegeMail", mvm),
                    ContentTransferEncoding = ContentEncoding.Base64,
                };

                var outmultipart = new Multipart("mixed");
                outmultipart.Add(body);
                //inmultipart.Add(attachments.First());
                // Bilder für Corporate Design, funktioniert leider nicht
                //outmultipart.Add(inmultipart);
                //outmultipart.Add(LoadInlinePicture("CCLogo.png", mvm.CCLogoFile));
                //outmultipart.Add(LoadInlinePicture("FBLogo.png", mvm.FacebookLogoFile));
                //outmultipart.Add(LoadInlinePicture("InstaLogo.png", mvm.InstaLogoFile));
                foreach (var attachment in attachments)
                {
                    outmultipart.Add(attachment);
                }

                message.Body = outmultipart;

                await emailSender.SendEmailAsync(message);
            }
            catch (Exception e)
            {
                logger.Error(e);
                string code = "#601";
                e = new Exception("Fehler beim Versenden der Anlegemail (" + e.Message + ") " + code, e);
                throw e;
            }
        }
Exemplo n.º 6
0
        public async Task SendMailAsync(string email, string subject, string body, string path)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(smtpSettings.SenderName, smtpSettings.SenderEmail));
                message.To.Add(new MailboxAddress(email, email));
                message.Subject = subject;
                var multipart = new Multipart("mixed");
                var streams   = new List <Stream>();

                if (path != null)
                {
                    var stream     = File.OpenRead(path);
                    var attachment = new MimePart(MimeTypes.GetMimeType(path))
                    {
                        Content                 = new MimeContent(stream),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(path)
                    };
                    multipart.Add(attachment);
                    streams.Add(stream);
                }


                var html = new TextPart("html")
                {
                    Text = body,
                };

                multipart.Add(html);
                message.Body = multipart;

                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.CheckCertificateRevocation          = false;
                    await client.ConnectAsync(smtpSettings.Server, smtpSettings.Port, true);

                    await client.AuthenticateAsync(smtpSettings.UserName, smtpSettings.Password);

                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }

                Console.WriteLine("Email sent");
                foreach (var stream in streams)
                {
                    stream.Dispose();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Email was not send {e.Message}");
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// 发邮件
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tos"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="attachments"></param>
        /// <returns></returns>
        public async static Task SendEmailAsync(Config config, List <MailAddress> tos, string subject, string message, params string[] attachments)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add((MailboxAddress)config.From);
            foreach (var to in tos)
            {
                emailMessage.To.Add(to as MailAddress);
            }

            emailMessage.Subject = subject;

            var alternative = new Multipart("alternative");

            if (config.IsHtml)
            {
                alternative.Add(new TextPart("html")
                {
                    Text = message
                });
            }
            else
            {
                alternative.Add(new TextPart("plain")
                {
                    Text = message
                });
            }

            if (attachments != null)
            {
                foreach (string f in attachments)
                {
                    var attachment = new MimePart()//("image", "png")
                    {
                        ContentObject           = new ContentObject(File.OpenRead(f), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = Path.GetFileName(f)
                    };
                    alternative.Add(attachment);
                }
            }
            emailMessage.Body = alternative;

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(config.Host, config.Port, config.UseSsl).ConfigureAwait(false);// SecureSocketOptions.None

                client.AuthenticationMechanisms.Remove("XOAUTH2");

                await client.AuthenticateAsync(config.MailFromAccount, config.MailPassword);

                await client.SendAsync(emailMessage).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
Exemplo n.º 8
0
        public static void send_Gmail(string[] To, string Subject, string Body, string From_name = "", string attachment_path = null, string ContentMediaType = null, string ContentSubType = null)
        {
            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(From_name, oauth2_account.mail_address));

            foreach (string str in To)
            {
                message.To.Add(new MailboxAddress("", str));
            }

            message.Subject = Subject;



            if (ContentMediaType != null)
            {
                var body = new TextPart("plain")
                {
                    Text = Body
                };

                var attachment = new MimePart(ContentMediaType, ContentSubType)
                {
                    ContentObject           = new ContentObject(File.OpenRead(attachment_path), ContentEncoding.Default),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName = Path.GetFileName(attachment_path)
                };

                var multipart = new Multipart("mixed");
                multipart.Add(body);
                multipart.Add(attachment);

                message.Body = multipart;
            }
            else
            {
                message.Body = new TextPart("plain")
                {
                    Text = Body
                };
            }

            using (var client = new SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls);

                //client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(oauth2_account.mail_address, oauth2_account.oauth2_access_Token);

                client.Send(message);
                client.Disconnect(true);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Sends an email containing the journey details to the nominated email address.
        /// </summary>
        /// <param name="journeyName">The unique journey name.</param>
        /// <param name="simpleJourneyDetailsFilePath">The file path to the simple journey details.</param>
        /// <param name="extendedJourneyDetailsFilePath">The file path to the extended journey details.</param>
        private void SendEmail(string journeyName, string simpleJourneyDetailsFilePath, string extendedJourneyDetailsFilePath)
        {
            // Get shared preferences
            ISharedPreferences settings = _context.GetSharedPreferences("settings", 0);

            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress("fleetTRACK", settings.GetString("SourceAddress", "")));
            message.To.Add(new MailboxAddress(settings.GetString("SendAddress", ""), settings.GetString("SendAddress", "")));
            message.Subject = journeyName;

            TextPart body = new TextPart("plain")
            {
                Text = "To whom it may concern,\n\tPlease see the attached trip details for billing purposes.\nKind regards,\nfleetTRACK"
            };

            // create an attachment for the file located at path
            MimePart simpleJourneyDetailsAttachment = new MimePart("text/csv")
            {
                ContentObject           = new ContentObject(File.OpenRead(simpleJourneyDetailsFilePath), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = Path.GetFileName(simpleJourneyDetailsFilePath)
            };

            // create an attachment for the file located at path
            MimePart extendedJourneyDetailsAttachment = new MimePart("text/csv")
            {
                ContentObject           = new ContentObject(File.OpenRead(extendedJourneyDetailsFilePath), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = Path.GetFileName(extendedJourneyDetailsFilePath)
            };

            // now create the multipart/mixed container to hold the message text and the attachments
            Multipart multipart = new Multipart("mixed");

            multipart.Add(body);
            multipart.Add(simpleJourneyDetailsAttachment);
            multipart.Add(extendedJourneyDetailsAttachment);

            // now set the multipart/mixed as the message body
            message.Body = multipart;

            using (SmtpClient client = new SmtpClient())
            {
                client.Connect(settings.GetString("SmtpServer", ""), settings.GetInt("SmtpPort", 25), false);

                // Since we don't have an OAuth2 token, disable the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                client.Authenticate(settings.GetString("SmtpUsername", ""), settings.GetString("SmtpPassword", ""));

                client.Send(message);
                client.Disconnect(true);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// MailKit组件
        /// </summary>
        /// <param name="from"></param>
        /// <param name="password"></param>
        /// <param name="to"></param>
        /// <param name="content"></param>
        /// <param name="title"></param>
        private void SendByMailKit(string from, string password, string to, string content, string title)
        {
            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(from, from));
            message.To.Add(new MailboxAddress(to, to));
            message.Subject = title;

            //message.Body = new TextPart(TextFormat.Html) { Text = content };
            var body = new TextPart(TextFormat.Html)
            {
                Text = content
            };
            MimeEntity entity = body;

            if (this.Attachments != null)
            {
                var mult = new Multipart("mixed")
                {
                    body
                };
                foreach (var att in this.Attachments)
                {
                    if (att.Data != null)
                    {
                        var attachment = string.IsNullOrWhiteSpace(att.ContentType) ? new MimePart() : new MimePart(att.ContentType);
                        attachment.Content            = new MimeContent(att.Data);
                        attachment.ContentDisposition = new ContentDisposition(ContentDisposition.Attachment);
                        //attachment.ContentTransferEncoding = att.ContentTransferEncoding;
                        //public ContentEncoding ContentTransferEncoding { get; set; } = ContentEncoding.Default;
                        attachment.FileName = ConvertHeaderToBase64(att.FileName, Encoding.UTF8);//解决附件中文名问题
                        mult.Add(attachment);
                    }
                }
                entity = mult;
            }
            message.Body = entity;

            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Timeout = 30000;
                client.CheckCertificateRevocation = false;

                // Smtp服务器
                client.Connect(this.Host, this.Port, false);

                // 登录: only needed if the SMTP server requires authenticationn
                client.Authenticate(from, password);

                // 发送
                client.Send(message);

                // 断开
                client.Disconnect(true);
            }
        }
Exemplo n.º 11
0
        private bool SendEmail(IEmailNotificationModel message)
        {
            try
            {
                if (message.Valid)
                {
                    var email = new MimeMessage
                    {
                        Subject = message.Subject
                    };

                    foreach (var from in message.From)
                    {
                        email.From.Add(MailboxAddress.Parse(from));
                    }

                    foreach (var to in message.To)
                    {
                        email.To.Add(MailboxAddress.Parse(to));
                    }

                    var multipart = new Multipart("mixed")
                    {
                        new TextPart(message.TextFormat)
                        {
                            Text = message.Text
                        }
                    };

                    foreach (var attachment in message.Attachments)
                    {
                        multipart.Add(new MimePart(attachment.MediaType, attachment.MediaSubtype)
                        {
                            Content                 = new MimeContent(new MemoryStream(Convert.FromBase64String(attachment.Base64))),
                            ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                            ContentTransferEncoding = ContentEncoding.Base64,
                            FileName                = attachment.Filename
                        });
                    }

                    email.Body = multipart;

                    using var smtp = new SmtpClient();
                    smtp.Connect(message.Config.Host, message.Config.Port, message.Config.SecureSocketOptions);
                    smtp.Authenticate(message.Config.Username, message.Config.Password);
                    smtp.Send(email);
                    smtp.Disconnect(true);
                }
            }
            catch (System.Exception)
            {
                // log
            }

            return(false);
        }
Exemplo n.º 12
0
        private static async Task TestClientConnectionAsync(MailDemonService demon, string server, string to, string file)
        {
            SmtpClient client = new SmtpClient()
            {
                SslProtocols = System.Security.Authentication.SslProtocols.None,
                Timeout      = 60000 // 60 secs
            };
            await client.ConnectAsync(server, 25, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable);

            try
            {
                await client.AuthenticateAsync(new NetworkCredential("no", "no"));
            }
            catch
            {
                // expected
            }

            await client.DisconnectAsync(false);

            await client.ConnectAsync(server, 25, MailKit.Security.SecureSocketOptions.StartTlsWhenAvailable);

            await client.AuthenticateAsync(new NetworkCredential(demon.Users.First().UserName, demon.Users.First().Password));

            MimeMessage msg = new MimeMessage();

            msg.From.Add(demon.Users.First().MailAddress);
            foreach (string toAddress in to.Split(',', ';'))
            {
                msg.To.Add(MailboxAddress.Parse(toAddress));
            }
            msg.Subject = "Test Subject";
            BodyBuilder bodyBuilder = new BodyBuilder();
            Multipart   multipart   = new Multipart("mixed");

            bodyBuilder.HtmlBody = "<html><body><b>Test Email Html Body Which is Bold 12345</b></body></html>";
            multipart.Add(bodyBuilder.ToMessageBody());
            if (file != null && File.Exists(file))
            {
                byte[] bytes      = System.IO.File.ReadAllBytes(file);
                var    attachment = new MimePart("binary", "bin")
                {
                    Content                 = new MimeContent(new MemoryStream(bytes), ContentEncoding.Binary),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Binary, // Base64 for DATA test, Binary for BINARYMIME test
                    FileName                = Path.GetFileName(file)
                };
                multipart.Add(attachment);
            }
            msg.Body = multipart;
            await client.SendAsync(msg);

            await client.DisconnectAsync(true);

            Console.WriteLine("Test message sent");
        }
Exemplo n.º 13
0
        public void TestArgumentExceptions()
        {
            var multipart = new Multipart();

            Assert.Throws <ArgumentNullException> (() => new Multipart((MimeEntityConstructorArgs)null));
            Assert.Throws <ArgumentNullException> (() => new Multipart((string)null));
            Assert.Throws <ArgumentNullException> (() => new Multipart("mixed", null));
            Assert.Throws <ArgumentException> (() => new Multipart("mixed", 5));

            Assert.Throws <ArgumentNullException> (() => multipart.Boundary = null);

            Assert.Throws <ArgumentNullException> (() => multipart.Add(null));
            Assert.Throws <ArgumentOutOfRangeException> (() => multipart.Insert(-1, new TextPart("plain")));
            Assert.Throws <ArgumentNullException> (() => multipart.Insert(0, null));
            Assert.Throws <ArgumentNullException> (() => multipart.Remove(null));
            Assert.Throws <ArgumentOutOfRangeException> (() => multipart.RemoveAt(-1));

            Assert.Throws <ArgumentNullException> (() => multipart.Contains(null));
            Assert.Throws <ArgumentNullException> (() => multipart.IndexOf(null));

            Assert.Throws <ArgumentOutOfRangeException> (() => multipart[0] = new TextPart("plain"));
            Assert.Throws <ArgumentNullException> (() => multipart[0]       = null);

            Assert.Throws <ArgumentNullException> (() => multipart.Accept(null));

            Assert.Throws <ArgumentOutOfRangeException> (() => multipart.CopyTo(new MimeEntity[0], -1));
            Assert.Throws <ArgumentNullException> (() => multipart.CopyTo(null, 0));

            Assert.Throws <ArgumentOutOfRangeException> (() => multipart.Prepare(EncodingConstraint.SevenBit, 1));

            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo((string)null));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo((Stream)null));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo((string)null, false));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo((Stream)null, false));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo(null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo(FormatOptions.Default, (Stream)null));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo(null, "fileName"));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo(FormatOptions.Default, (string)null));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo(null, Stream.Null, false));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo(FormatOptions.Default, (Stream)null, false));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo(null, "fileName", false));
            Assert.Throws <ArgumentNullException> (() => multipart.WriteTo(FormatOptions.Default, (string)null, false));

            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync((string)null));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync((Stream)null));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync((string)null, false));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync((Stream)null, false));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync(null, Stream.Null));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync(FormatOptions.Default, (Stream)null));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync(null, "fileName"));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync(FormatOptions.Default, (string)null));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync(null, Stream.Null, false));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync(FormatOptions.Default, (Stream)null, false));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync(null, "fileName", false));
            Assert.ThrowsAsync <ArgumentNullException> (async() => await multipart.WriteToAsync(FormatOptions.Default, (string)null, false));
        }
Exemplo n.º 14
0
        public async Task Generate(string email, string mailTemplate, object mailData, string subject, Tuple <byte[], string>[] attachments = null)
        {
            var html = viewRender.Render(mailTemplate, mailData);

            var mimeMessage = new MimeMessage();

            mimeMessage.From.Add(new MailboxAddress(mailSettings.From, mailSettings.Login));
            mimeMessage.To.Add(new MailboxAddress("", email));
            mimeMessage.Subject = subject;

            var multipart = new Multipart("mixed");

            var body = new TextPart(MimeKit.Text.TextFormat.Html)
            {
                Text = html
            };

            multipart.Add(body);

            if (!(attachments is null))
            {
                for (var i = 0; i < attachments.Length; i++)
                {
                    var typeAndExt = attachments[i].Item2.Split('/');
                    var file       = new MimePart(typeAndExt[0], typeAndExt[1])
                    {
                        Content                 = new MimeContent(new MemoryStream(attachments[i].Item1), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = $"Attachment{i + 1}"
                    };

                    multipart.Add(file);
                }
            }

            mimeMessage.Body = multipart;

            try
            {
                using (var client = new SmtpClient())
                {
                    await client.ConnectAsync(mailSettings.ServiceUri, mailSettings.ServicePort, true);

                    await client.AuthenticateAsync(mailSettings.Login, mailSettings.Password);

                    await client.SendAsync(mimeMessage);

                    await client.DisconnectAsync(true);
                }
            }
            catch (System.Exception)
            {
                throw new ApiException(HttpStatusCode.Conflict, ApiError.MailServerDeclinedEmail);
            }
        }
Exemplo n.º 15
0
        static MimeMessage CreateMimeMessage(ConsumeContext <SendMail> context)
        {
            MimeMessage mimeMessage = new MimeMessage
            {
                Importance = (MessageImportance)Enum.Parse(typeof(MessageImportance), context.Message.Importance),
                Priority   = (MessagePriority)Enum.Parse(typeof(MessagePriority), context.Message.Priority),
                XPriority  = (XMessagePriority)Enum.Parse(typeof(XMessagePriority), context.Message.XPriority),
                MessageId  = context.Message.MessageId,
                Subject    = context.Message.Subject,
            };

            var mimeParts =
                context.Message.AttachmentsMeta
                .Select(m => m.Split(new[] { char.ConvertFromUtf32(31) }, StringSplitOptions.None))
                .Select(m =>
            {
                int offset    = int.Parse(m[3]);
                int length    = int.Parse(m[4]);
                byte[] buffer = new byte[length];
                Array.Copy(context.Message.AttachmentsContent, offset, buffer, 0, length);

                return(new MimePart
                {
                    ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName = m[0],
                    Content = new MimeContent(new MemoryStream(buffer)),
                    ContentType =
                    {
                        MediaType    = m[1],
                        MediaSubtype = m[2]
                    }
                });
            })
                .ToArray();

            if (mimeParts.Length > 0)
            {
                TextFormat textFormat = string.IsNullOrWhiteSpace(context.Message.HtmlBody) ? TextFormat.Text : TextFormat.Html;

                TextPart textPart = new TextPart(textFormat)
                {
                    Text = textFormat == TextFormat.Html ? context.Message.HtmlBody : context.Message.TextBody
                };

                var multipart = new Multipart("mixed")
                {
                    textPart
                };
                Array.ForEach(mimeParts, multipart.Add);

                mimeMessage.Body = multipart;
            }

            return(mimeMessage);
        }
Exemplo n.º 16
0
        public async Task SendEMailAsync(string subject, string content, IEnumerable <MailboxAddress> fromAddress, IEnumerable <MailboxAddress> toAddress,
                                         TextFormat textFormat = TextFormat.Plain, IEnumerable <MailKitAttachmentInfo> attachments = null, bool dispose = true)
        {
            var message = new MimeMessage();

            message.From.AddRange(fromAddress);
            message.To.AddRange(toAddress);
            message.Subject = subject;
            var body = new TextPart(textFormat)
            {
                Text = content
            };
            MimeEntity entity = body;

            if (attachments != null)
            {
                var mult = new Multipart("mixed")
                {
                    body
                };
                foreach (var att in attachments)
                {
                    if (att.Stream != null)
                    {
                        var attachment = string.IsNullOrWhiteSpace(att.ContentType) ? new MimePart() : new MimePart(att.ContentType);
                        attachment.Content            = new MimeContent(att.Stream);
                        attachment.ContentDisposition = new ContentDisposition(ContentDisposition.Attachment);
                        // attachment.ContentTransferEncoding = att.ContentTransferEncoding;
                        attachment.FileName = ConvertHeaderToBase64(att.FileName, Encoding.UTF8);//解决附件中文名问题
                        mult.Add(attachment);
                    }
                }
                entity = mult;
            }
            message.Body = entity;
            message.Date = DateTime.Now;
            using (var client = new SmtpClient())
            {
                //创建连接
                await client.ConnectAsync(_mailKitConfig.Host, _mailKitConfig.Port, _mailKitConfig.UseSsl).ConfigureAwait(false);

                await client.AuthenticateAsync(_mailKitConfig.UserAddress, _mailKitConfig.Password).ConfigureAwait(false);

                await client.SendAsync(message).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);

                if (dispose && attachments != null)
                {
                    foreach (var att in attachments)
                    {
                        att.Dispose();
                    }
                }
            }
        }
Exemplo n.º 17
0
        // public EmailMessageSenderOptions Options { get; private set; }
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            if (!email.IsEmail())
            {
                return;
            }
            if (mailConfig.RequireValid)
            {
                MimeMessage mailmessage = new MimeMessage();
                mailmessage.From.Add(new MailboxAddress(mailConfig.Title, mailConfig.Uid));
                mailmessage.To.Add(new MailboxAddress(subject, email));
                mailmessage.Subject = subject;

                var plain = new TextPart("plain")
                {
                    Text = message
                };
                var html = new TextPart("html")
                {
                    Text = message
                };

                var alternative = new Multipart("alternative")
                {
                    plain,
                    html
                };

                var multipart = new Multipart("mixed")
                {
                    alternative
                };
                mailmessage.Body = multipart;

                using (var client = new SmtpClient())
                {
                    client.Connect(mailConfig.Server, mailConfig.Port, false);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    client.Authenticate(mailConfig.Uid, mailConfig.Pwd);
                    try
                    {
                        await client.SendAsync(mailmessage);

                        await client.DisconnectAsync(true);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex.Message, ex);
#if Debug
                        throw;
#endif
                    }
                }
            }
        }
Exemplo n.º 18
0
        public async Task SendAsync(Email emailRequest)
        {
            if (options.Enabled)
            {
                var format  = emailRequest.IsBodyHtml ? MimeKit.Text.TextFormat.Html : MimeKit.Text.TextFormat.Text;
                var builder = new BodyBuilder();

                builder.TextBody = emailRequest.Body;
                builder.HtmlBody = emailRequest.Body;

                var multipart = new Multipart("mixed");
                multipart.Add(new TextPart(format)
                {
                    Text = emailRequest.Body
                });

                if (emailRequest.FileName != null && emailRequest.Attachment != null)
                {
                    Stream stream = new MemoryStream(emailRequest.Attachment);
                    // create an image attachment for the file located at path
                    var attachment = new MimePart("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    {
                        Content                 = new MimeContent(stream),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(emailRequest.FileName)
                    };
                    multipart.Add(attachment);
                }

                var msg = new MimeMessage
                {
                    Subject = emailRequest.Subject,
                    Body    = multipart
                };

                msg.From.Add(new MailboxAddress(options.Email, options.Email));
                msg.To.Add(new MailboxAddress(emailRequest.NameTo, emailRequest.To));

                using var client = new SmtpClient();

                client.Connect(options.Host, options.Port);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                // O usar https://stackoverflow.com/a/33501052
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(options.Email, options.Password);

                await client.SendAsync(msg);

                client.Disconnect(true);
            }
        }
Exemplo n.º 19
0
        public void imapSaveAttachedFile(dbData3060DataContext p_dbData3060, string filename, byte[] data, bool bTilPBS)
        {
            string local_filename = filename.Replace('.', '_') + ".txt";

            MimeMessage message = new MimeMessage();
            TextPart    body;

            message.To.Add(new MailboxAddress(@"Regnskab Puls3060", @"*****@*****.**"));
            message.From.Add(new MailboxAddress(@"Regnskab Puls3060", @"*****@*****.**"));

            if (bTilPBS)
            {
                message.Subject = "Til PBS: " + local_filename;
                body            = new TextPart("plain")
                {
                    Text = @"Til PBS: " + local_filename
                };
            }
            else
            {
                message.Subject = "Fra PBS: " + local_filename;
                body            = new TextPart("plain")
                {
                    Text = @"Fra PBS: " + local_filename
                };
            }

            var attachment = new MimePart("text", "plain")
            {
                ContentObject           = new ContentObject(new MemoryStream(data), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = local_filename
            };

            var multipart = new Multipart("mixed");

            multipart.Add(body);
            multipart.Add(attachment);

            message.Body = multipart;

            using (var client = new ImapClient())
            {
                client.Connect("imap.gigahost.dk", 993, true);
                client.AuthenticationMechanisms.Remove("XOAUTH");
                client.Authenticate(clsApp.GigaHostImapUser, clsApp.GigaHostImapPW);

                var PBS = client.GetFolder("INBOX.PBS");
                PBS.Open(FolderAccess.ReadWrite);
                PBS.Append(message);
                PBS.Close();

                client.Disconnect(true);
            }
        }
Exemplo n.º 20
0
        public static int SendEmail(string from, string fromTitle, string to, string toTitle, string subject, string bodyContent, string path, string yourEmail, string yourPass)
        {
            try
            {
                var body = new TextPart("plain")
                {
                    Text = bodyContent
                };

                // Smtp Server
                string SmtpServer = "smtp.gmail.com";
                // Smtp Port Number
                int SmtpPortNumber = 587;
                var mimeMessage    = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(fromTitle, from));
                mimeMessage.To.Add(new MailboxAddress(toTitle, to));
                mimeMessage.Subject = subject;


                // now create the multipart/mixed container to hold the message text and the
                // image attachment
                var multipart = new Multipart("mixed");
                multipart.Add(body);

                // add attackment
                // create an image attachment for the file located at path
                if (path != "")
                {
                    var attachment = new MimePart()
                    {
                        ContentObject           = new ContentObject(System.IO.File.OpenRead(path), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = Path.GetFileName(path)
                    };
                    multipart.Add(attachment);
                }

                // now set the multipart/mixed as the message body
                mimeMessage.Body = multipart;

                using (var client = new SmtpClient())
                {
                    client.Connect(SmtpServer, SmtpPortNumber, false);
                    //client.Authenticate("your email", "your pass");

                    client.Send(mimeMessage);
                    client.Disconnect(true);
                }
                return(1);
            }
            catch
            {
                return(0);
            }
        }
        public void SendEmailAsync(List <string> emails, string subject, string message, List <MimePart> attachments)
        {
            var emailMessage = new MimeMessage();

            emailMessage.From.Add(new MailboxAddress("Sistema Vida Nova", "*****@*****.**"));
            emailMessage.To.Add(new MailboxAddress("", "*****@*****.**"));
            foreach (string email in emails)
            {
                emailMessage.Bcc.Add(new MailboxAddress("", email));
            }
            emailMessage.Subject = subject;
            if (attachments.Count > 0) // se contem anexos
            {
                var multipart = new Multipart("mixed");
                multipart.Add(new TextPart(TextFormat.Html)
                {
                    Text = message
                });                                 // texto da mensagem
                foreach (var attach in attachments) // anexos
                {
                    multipart.Add(attach);
                }
                emailMessage.Body = multipart;
            }
            else
            {
                emailMessage.Body = new TextPart(TextFormat.Html)
                {
                    Text = "<div>" + message + "</div>"
                };
            }


            using (var client = new SmtpClient())
            {
                //client.LocalDomain = "localhost";//colocar o dominio do sistema ex: vidanova.com.br

                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;


                client.Connect("smtp.gmail.com", 465, true);// 465 587

                // 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
                client.Authenticate("*****@*****.**", "Vid@nova");

                client.Send(emailMessage);
                client.Disconnect(true);
            }
        }
Exemplo n.º 22
0
        ///<summary>Helper method that creates a new MIME message based on the parameters (to, cc, bcc, from, and body)</summary>
        private static MimeMessage CreateMIMEMsg(BasicEmailAddress emailAddress, BasicEmailMessage emailMessage)
        {
            MimeMessage mimeMsg   = new MimeMessage();
            Multipart   multipart = new Multipart();

            mimeMsg.From.Add(new MailboxAddress(emailAddress.EmailUsername));
            if (!emailMessage.Subject.IsNullOrEmpty())
            {
                mimeMsg.Subject = emailMessage.Subject;
            }
            //Create MailAddress objects for all addresses.
            //MailAddress will automatically parse out "DisplayName" <*****@*****.**> and every variation
            MailAddress toAddress = new MailAddress(emailMessage.ToAddress.Trim());

            mimeMsg.To.Add(new MailboxAddress(toAddress.DisplayName, toAddress.Address));
            if (!emailMessage.CcAddress.IsNullOrEmpty())
            {
                MailAddress ccAddress = new MailAddress(emailMessage.CcAddress.Trim());
                mimeMsg.Cc.Add(new MailboxAddress(ccAddress.DisplayName, ccAddress.Address));
            }
            if (!emailMessage.BccAddress.IsNullOrEmpty())
            {
                MailAddress bccAddress = new MailAddress(emailMessage.BccAddress.Trim());
                mimeMsg.Cc.Add(new MailboxAddress(bccAddress.DisplayName, bccAddress.Address));
            }
            if (emailMessage.ListAttachments != null)
            {
                foreach (Tuple <string, string> attachmentPath in emailMessage.ListAttachments)
                {
                    multipart.Add(new MimePart()
                    {
                        Content                 = new MimeContent(File.OpenRead(attachmentPath.Item1)),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(attachmentPath.Item1)
                    });
                }
            }
            if (emailMessage.IsHtml)
            {
                multipart.Add(new TextPart(MimeKit.Text.TextFormat.Html)
                {
                    Text = emailMessage.HtmlBody
                });
            }
            else
            {
                multipart.Add(new TextPart()
                {
                    Text = emailMessage.BodyText
                });
            }
            mimeMsg.Body = multipart;
            return(mimeMsg);
        }
Exemplo n.º 23
0
        /// <summary>
        /// 获取发送数据对象
        /// http://www.mimekit.net/docs/html/Introduction.htm
        /// </summary>
        /// <param name="emailModel"></param>
        /// <returns></returns>
        public MimeMessage GetMimeMessage(EmailModel emailModel, bool isUsingDefault = true)
        {
            if (isUsingDefault)
            {
                emailModel.MailFromAddress = _fromAddress;
                emailModel.MailFromUser    = _fromName;
                emailModel.Host            = _host;
                emailModel.Password        = _fromPassword;
                emailModel.Port            = _port;
            }

            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(emailModel.MailFromUser, emailModel.MailFromAddress));
            message.To.Add(new MailboxAddress(emailModel.MailToUser, emailModel.MailToAddress));
            message.Subject = emailModel.Subject;

            //邮件正文
            var alternativeBody = new MultipartAlternative();
            var textBody        = new TextPart(TextFormat.Plain)
            {
                Text = emailModel.TextBody
            };
            var htmlBody = new TextPart(TextFormat.Html)
            {
                Text = emailModel.HtmlBody
            };

            alternativeBody.Add(textBody);
            alternativeBody.Add(htmlBody);
            Multipart multipart = new Multipart("mixed");

            multipart.Add(alternativeBody);

            //附件
            if (emailModel.Attachments != null && emailModel.Attachments.Count >= 0)
            {
                for (int i = 0; i < emailModel.Attachments.Count; i++)
                {
                    var      path       = emailModel.Attachments[i];
                    MimePart attachment = new MimePart()
                    {
                        Content                 = new MimeContent(File.OpenRead(path), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(path)
                    };
                    multipart.Add(attachment);
                }
            }

            message.Body = multipart;
            return(message);
        }
Exemplo n.º 24
0
        private string SendEmail(SendModel model)
        {
            var attachment = new MimePart("document", "pdf")
            {
                Content                 = new MimeContent(new MemoryStream(model.Attachment)),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = "document.pdf"
            };

            MimeMessage message = new MimeMessage {
                Subject = model.Subject
            };
            var body = new TextPart(TextFormat.Plain)
            {
                Text = model.Message ?? string.Empty
            };
            var multipart = new Multipart("mixed")
            {
                body, attachment
            };

            message.Body = multipart;

            if (model.EmailAddresses.Count <= 0)
            {
                return(DicNotificationStatus.Codes.EmailNotFound);
            }

            message.From.Add(new MailboxAddress("NIIS", model.Credentials.EmailFrom));

            foreach (var emailAddress in model.EmailAddresses)
            {
                message.To.Add(new MailboxAddress("", emailAddress));
            }


            try
            {
                using (SmtpClient client = new SmtpClient())
                {
                    client.Connect(model.Credentials.SmtpServer, model.Credentials.SmtpPort, true);
                    client.Authenticate(model.Credentials.EmailFrom, model.Credentials.EmailPassword);
                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception e)
            {
                return(DicNotificationStatus.Codes.EmailSendFail);
            }

            return(DicNotificationStatus.Codes.EmailSend);
        }
Exemplo n.º 25
0
        public async Task SendMessageAsync(string to          = testUserEmail, string subject = defaultSubject,
                                           string messageBody = defaultMessageText)
        {
            // Creare message
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(MailSettings.Email));
            message.To.Add(new MailboxAddress(to));
            message.Subject = subject;

            //create text
            var bodyText = new TextPart("plain")
            {
                Text = MessageBuilder(messageBody)
            };

            // create and get path to the file
            UserActionReportHelper reportHelper = new UserActionReportHelper();
            await reportHelper.GenerateReportFile();

            string path = reportHelper.GetReportPath();

            // create an attachment
            var attachment = new MimePart()
            {
                Content                 = new MimeContent(File.OpenRead(path), ContentEncoding.Default),
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName                = Path.GetFileName(path)
            };

            // create the multipart/mixed container
            var multipart = new Multipart("mixed")
            {
                bodyText,
                attachment
            };

            message.Body = multipart;

            // Send the message
            using (var client = new SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(MailSettings.SMTPServer, Int32.Parse(MailSettings.Port), MailKit.Security.SecureSocketOptions.SslOnConnect);
                client.Authenticate(MailSettings.Email, MailSettings.Password);

                await client.SendAsync(message);

                client.Disconnect(true);
            }
        }
Exemplo n.º 26
0
 public void TryCreateMultipart_NullParts()
 {
     try
     {
         var part = new Multipart(null);
         Assert.Fail("Invalid parts!");
     }
     catch (Exception e)
     {
         Assert.IsTrue(e.Message.Contains(NFX.Web.StringConsts.MULTIPART_PARTS_COULDNT_BE_EMPTY_ERROR));
     }
 }
Exemplo n.º 27
0
        public static async Task EmailScheduleAsync(string smtpUser, string smtpPass, string fromString, string[] toStrings, string[] ccStrings, string subject, string body, string csvFileName, string csvFile)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(fromString));

            foreach (var to in toStrings)
            {
                message.To.Add(new MailboxAddress(to));
            }

            message.Subject = subject;

            foreach (var cc in ccStrings)
            {
                message.Cc.Add(new MailboxAddress(cc));
            }

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(csvFile)))
            {
                var attachment = new MimePart("text/csv")
                {
                    ContentObject           = new ContentObject(ms),
                    ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName = csvFileName
                };

                var bodyPart = new TextPart("plain")
                {
                    Text = body
                };
                var mp = new Multipart("mixed")
                {
                    bodyPart, attachment
                };

                message.Body = mp;

                using (var client = new SmtpClient())
                {
                    var creds = new NetworkCredential(smtpUser, smtpPass);

                    await client.ConnectAsync("smtp.gmail.com", 587).ConfigureAwait(false);

                    await client.AuthenticateAsync(creds);

                    await client.SendAsync(message).ConfigureAwait(false);

                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 28
0
        public void TestEpilogueFolding()
        {
            const string text     = "This is a multipart epilogue.";
            const string expected = "\nThis is a multipart epilogue.\n";
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            var actual = Multipart.FoldPreambleOrEpilogue(options, text, true);

            Assert.AreEqual(expected, actual, "Folded multipart preamble does not match.");
        }
Exemplo n.º 29
0
        public async Task<PasswordForgotEmailResultView> SentForgotEmailAsync(string email, string url)
        {
            if (_isDemo)
                return new PasswordForgotEmailResultView { IsSentEmail = false, Message = (int)Constants.Errors.ErrorSendEmail };
            
            var user = await _userManager.FindByEmailAsync(email);
            if (user == null)
            {
                return new PasswordForgotEmailResultView { IsSentEmail = false, Message = (int)Constants.Errors.EmailDoesntExist };
            }

            if (!user.IsActive)
            {
                return new PasswordForgotEmailResultView { IsSentEmail = false, Message = (int)Constants.Errors.UserIsArchived };
            }

            var token = await GetForgotToken(user);
            var passwordResetLinkValidForHrs = int.Parse(_configuration["PasswordResetLinkValidForHrs"]);
            var userForgotPassRequest = Uow.UserForgotPassRequestRepository.CreateUserForgotPassRequest(email, passwordResetLinkValidForHrs, token);

            if (userForgotPassRequest == null)
            {
                return new PasswordForgotEmailResultView { IsSentEmail = false, Message = (int)Constants.Errors.ErrorSendEmail };
            }

            var link = $"{url}/forgot-password/enter-new-password?restoreCode={userForgotPassRequest.UserForgotPassRequestUid}";
            var subject = "Reset your CoralTime password.";

            var body = new TextPart("html")
            {
                Text = $@"CoralTime received a request to reset your password.<br /><br />
                        To reset your password, click this link or copy the URL below and paste it into your web browser's navigation bar:<br />
                        {link}<br /><br />
                        Please note: This link will expire in {passwordResetLinkValidForHrs} hours. If it has already expired, please go back to {url} and click the Forgot Password?<br /><br />
                        Best wishes,<br />
                        the CoralTime team"
            };

            var multipart = new Multipart { body };

            var emailSender = new EmailSender(_configuration);

            emailSender.CreateSimpleMessage(email, multipart, subject);
            try
            {
                await emailSender.SendMessageAsync();
                return new PasswordForgotEmailResultView { IsSentEmail = true, Message = (int)Constants.Errors.None };
            }
            catch (Exception)
            {
                return new PasswordForgotEmailResultView { IsSentEmail = false, Message = (int)Constants.Errors.ErrorSendEmail };
            }
        }
Exemplo n.º 30
0
        public void TestPreambleFolding()
        {
            const string text     = "This is a multipart MIME message. If you are reading this text, then it means that your mail client does not support MIME.\n";
            const string expected = "This is a multipart MIME message. If you are reading this text, then it means\nthat your mail client does not support MIME.\n";
            var          options  = FormatOptions.Default.Clone();

            options.NewLineFormat = NewLineFormat.Unix;

            var actual = Multipart.FoldPreambleOrEpilogue(options, text, false);

            Assert.AreEqual(expected, actual, "Folded multipart preamble does not match.");
        }
Exemplo n.º 31
0
        static Multipart CreateImapExampleInnerMultipart(List <MimeEntity> parents)
        {
            var mixed = new Multipart("mixed");

            parents.Add(mixed);
            mixed.Add(new MimePart("image", "gif"));

            parents.Add(mixed);
            mixed.Add(CreateImapExampleInnerMessageRfc822(parents));

            return(mixed);
        }
Exemplo n.º 32
0
 private KeyValuePair<string, string>[] GetSheetMaps(Multipart multipart)
 {
     KeyValuePair<string, string>[] result = null;
     var reg = new Regex(SheetsReg, RegexOptions.IgnoreCase);
     foreach (var part in multipart.Parts)
     {
         var matches = reg.Matches(part.ToString());
         if (matches.Count > 0)
         {
             result = matches.Cast<Match>().Select(i => GetMap(i.Value)).ToArray();
             break;
         }
     }
     return result;
 }
Exemplo n.º 33
0
		public void TestLongPreamble ()
		{
			var multipart = new Multipart ("alternative");
			var multiline = "This is a part in a (multipart) message generated with the MimeKit library. " + 
			                "All of the parts of this message are identical, however they've been encoded " +
			                "for transport using different methods.";
			var expected = "This is a part in a (multipart) message generated with the MimeKit library.\n" +
			               "All of the parts of this message are identical, however they've been encoded\n" +
			               "for transport using different methods.\n";

			if (FormatOptions.Default.NewLineFormat != NewLineFormat.Unix)
				expected = expected.Replace ("\n", "\r\n");

			multipart.Preamble = multiline;

			Assert.AreEqual (expected, multipart.Preamble);
		}
Exemplo n.º 34
0
		public void TestBasicFunctionality ()
		{
			var multipart = new Multipart ();

			Assert.IsNotNullOrEmpty (multipart.Boundary, "Boundary");
			Assert.IsFalse (multipart.IsReadOnly, "IsReadOnly");

			multipart.Boundary = "__Next_Part_123";

			Assert.AreEqual ("__Next_Part_123", multipart.Boundary);

			var generic = new MimePart ("application", "octet-stream") { ContentObject = new ContentObject (new MemoryStream ()), IsAttachment = true };
			var plain = new TextPart ("plain") { Text = "This is some plain text." };

			multipart.Add (generic);
			multipart.Insert (0, plain);

			Assert.AreEqual (2, multipart.Count, "Count");

			Assert.IsTrue (multipart.Contains (generic), "Contains");
			Assert.AreEqual (0, multipart.IndexOf (plain), "IndexOf");
			Assert.IsTrue (multipart.Remove (generic), "Remove");
			Assert.IsFalse (multipart.Remove (generic), "Remove 2nd time");

			multipart.RemoveAt (0);

			Assert.AreEqual (0, multipart.Count, "Count");

			multipart.Add (generic);
			multipart.Add (plain);

			Assert.AreEqual (generic, multipart[0]);
			Assert.AreEqual (plain, multipart[1]);

			multipart[0] = plain;
			multipart[1] = generic;

			Assert.AreEqual (plain, multipart[0]);
			Assert.AreEqual (generic, multipart[1]);

			multipart.Clear ();

			Assert.AreEqual (0, multipart.Count, "Count");
		}
Exemplo n.º 35
0
        unsafe BoundaryType ConstructMultipart(Multipart multipart, byte* inbuf)
        {
            var boundary = multipart.Boundary;

            if (boundary == null) {
                Debug.WriteLine ("Multipart without a boundary encountered!");

                // Note: this will scan all content into the preamble...
                return MultipartScanPreamble (multipart, inbuf);
            }

            PushBoundary (boundary);

            var found = MultipartScanPreamble (multipart, inbuf);
            if (found == BoundaryType.ImmediateBoundary)
                found = MultipartScanSubparts (multipart, inbuf);

            if (found == BoundaryType.ImmediateEndBoundary) {
                // consume the end boundary and read the epilogue (if there is one)
                SkipLine (inbuf);
                PopBoundary ();

                return MultipartScanEpilogue (multipart, inbuf);
            }

            // We either found the end of the stream or we found a parent's boundary
            PopBoundary ();

            if (found == BoundaryType.ParentEndBoundary && FoundImmediateBoundary (inbuf, true))
                return BoundaryType.ImmediateEndBoundary;

            if (found == BoundaryType.ParentBoundary && FoundImmediateBoundary (inbuf, false))
                return BoundaryType.ImmediateBoundary;

            return found;
        }
Exemplo n.º 36
0
 unsafe BoundaryType MultipartScanPreamble(Multipart multipart, byte* inbuf)
 {
     using (var memory = new MemoryStream ()) {
         var found = ScanContent (inbuf, memory, false);
         multipart.RawPreamble = memory.ToArray ();
         return found;
     }
 }
Exemplo n.º 37
0
		/// <summary>
		/// Constructs the message body based on the text-based bodies, the linked resources, and the attachments.
		/// </summary>
		/// <remarks>
		/// Combines the <see cref="Attachments"/>, <see cref="LinkedResources"/>, <see cref="TextBody"/>,
		/// and <see cref="HtmlBody"/> into the proper MIME structure suitable for display in many common
		/// mail clients.
		/// </remarks>
		/// <returns>The message body.</returns>
		public MimeEntity ToMessageBody ()
		{
			Multipart alternative = null;
			MimeEntity body = null;

			if (!string.IsNullOrEmpty (TextBody)) {
				var text = new TextPart ("plain");
				text.Text = TextBody;

				if (!string.IsNullOrEmpty (HtmlBody)) {
					alternative = new Multipart ("alternative");
					alternative.Add (text);
					body = alternative;
				} else {
					body = text;
				}
			}

			if (!string.IsNullOrEmpty (HtmlBody)) {
				var text = new TextPart ("html");
				MimeEntity html;

				text.ContentId = MimeUtils.GenerateMessageId ();
				text.Text = HtmlBody;

				if (LinkedResources.Count > 0) {
					var related = new MultipartRelated {
						Root = text
					};

					foreach (var resource in LinkedResources)
						related.Add (resource);

					html = related;
				} else {
					html = text;
				}

				if (alternative != null)
					alternative.Add (html);
				else
					body = html;
			}

			if (Attachments.Count > 0) {
				var mixed = new Multipart ("mixed");

				if (body != null)
					mixed.Add (body);

				foreach (var attachment in Attachments)
					mixed.Add (attachment);

				body = mixed;
			}

			return body ?? new TextPart ("plain") { Text = string.Empty };
		}
Exemplo n.º 38
0
		/// <summary>
		/// Visit the abstract multipart MIME entity.
		/// </summary>
		/// <remarks>
		/// Visits the abstract multipart MIME entity.
		/// </remarks>
		/// <param name="multipart">The multipart MIME entity.</param>
		protected internal virtual void VisitMultipart (Multipart multipart)
		{
			VisitMimeEntity (multipart);
			VisitChildren (multipart);
		}
Exemplo n.º 39
0
		protected override void VisitMultipart (Multipart multipart)
		{
			foreach (var part in multipart) {
				if (part is MultipartAlternative)
					part.Accept (this);
				else if (part is MultipartRelated)
					part.Accept (this);
				else if (part is TextPart)
					part.Accept (this);
			}
		}
Exemplo n.º 40
0
		static bool TryGetMultipartAlternativeBody (Multipart multipart, bool html, out string body)
		{
			// walk the multipart/alternative children backwards from greatest level of faithfulness to the least faithful
			for (int i = multipart.Count - 1; i >= 0; i--) {
				var related = multipart[i] as MultipartRelated;
				TextPart text;

				if (related != null) {
					text = related.Root as TextPart;
				} else {
					var mpart = multipart[i] as Multipart;

					text = multipart[i] as TextPart;

					if (mpart != null && mpart.ContentType.Matches ("multipart", "alternative")) {
						// Note: nested multipart/alternatives make no sense... yet here we are.
						if (TryGetMultipartAlternativeBody (mpart, html, out body))
							return true;
					}
				}

				if (text != null && (html ? text.IsHtml : text.IsPlain)) {
					body = text.Text;
					return true;
				}
			}

			body = null;

			return false;
		}
Exemplo n.º 41
0
		static bool TryGetMultipartBody (Multipart multipart, TextFormat format, out string body)
		{
			var alternative = multipart as MultipartAlternative;

			if (alternative != null) {
				body = alternative.GetTextBody (format);
				return body != null;
			}

			var related = multipart as MultipartRelated;
			Multipart multi;
			TextPart text;

			if (related == null) {
				// Note: This is probably a multipart/mixed... and if not, we can still treat it like it is.
				for (int i = 0; i < multipart.Count; i++) {
					multi = multipart[i] as Multipart;

					// descend into nested multiparts, if there are any...
					if (multi != null) {
						if (TryGetMultipartBody (multi, format, out body))
							return true;

						// The text body should never come after a multipart.
						break;
					}

					text = multipart[i] as TextPart;

					// Look for the first non-attachment text part (realistically, the body text will
					// preceed any attachments, but I'm not sure we can rely on that assumption).
					if (text != null && !text.IsAttachment) {
						if (text.IsFormat (format)) {
							body = MultipartAlternative.GetText (text);
							return true;
						}

						// Note: the first text/* part in a multipart/mixed is the text body.
						// If it's not in the format we're looking for, then it doesn't exist.
						break;
					}
				}
			} else {
				// Note: If the multipart/related root document is HTML, then this is the droid we are looking for.
				var root = related.Root;

				text = root as TextPart;

				if (text != null) {
					body = text.IsFormat (format) ? text.Text : null;
					return body != null;
				}

				// maybe the root is another multipart (like multipart/alternative)?
				multi = root as Multipart;

				if (multi != null)
					return TryGetMultipartBody (multi, format, out body);
			}

			body = null;

			return false;
		}
            // called when a multipart/* part is found.
            //
            // we are interested in the `multipart/report; report-type=delivery-status` part. it
            // contains the parts that decribe the bounce.
            //
            // See https://tools.ietf.org/html/rfc3464
            // See https://github.com/jstedfast/MimeKit/blob/master/MimeKit/MessageDeliveryStatus.cs
            // See CreateEntity method at https://github.com/jstedfast/MimeKit/blob/master/MimeKit/ParserOptions.cs
            // See https://github.com/jstedfast/MimeKit/blob/master/MimeKit/MimeParser.cs
            protected override void VisitMultipart(Multipart multipart)
            {
                base.VisitMultipart(multipart);

                // save the multipart/report parts.
                if (multipart.ContentType.MediaSubtype == "report" && multipart.ContentType.Parameters["report-type"] == "delivery-status")
                {
                    if (multipart.Count > 0)
                    {
                        Result.DeliveryNotificationPart = multipart[0];
                    }

                    if (multipart.Count > 1)
                    {
                        Result.DeliveryStatus = multipart[1] as MessageDeliveryStatus;
                    }

                    if (multipart.Count > 2)
                    {
                        Result.UndeliveredMessagePart = multipart[2];
                    }
                }
            }
Exemplo n.º 43
0
 public MHTWorkBook(Stream stream)
 {
     var multipart = new Multipart(stream);
     Worksheets = CreateSheets(multipart);
 }
Exemplo n.º 44
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("key", TwitPicKey);

                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (Exception /*e*/)
            {
                //Socket exception 10054 could occur when sending large files.
                // Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 45
0
 private IWorksheet[] CreateSheets(Multipart multipart)
 {
     return GetSheetMaps(multipart).Select(i => new MHTWorksheet(i.Key,
             multipart.Parts.FirstOrDefault(j => j.Location.Contains(i.Value)))).ToArray();
 }
Exemplo n.º 46
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 60000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("source", "PockeTwit");
                contents.Add("sourceLink", "http://code.google.com/p/pocketwit/");
                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    contents.Add("message", ppo.Message);
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);
                return contents.UploadXML(request);
            }
            catch (WebException ex)
            {
                if (ex.Response is HttpWebResponse)
                {
                    using(HttpWebResponse response = ex.Response as HttpWebResponse)
                    {
                        OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, String.Format(PockeTwit.Localization.XmlBasedResourceManager.GetString("Error Uploading: Service returned message '{0}'"), response.StatusDescription), ppo.Filename));
                    }
                }
                else if (ex.InnerException is System.Net.Sockets.SocketException)
                {
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, ex.Message, ppo.Filename));
                }
                else
                    OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD, ppo.Filename));
                return null;
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 47
0
        /// <summary>
        /// Post a picture
        /// </summary>
        /// <param name="postData"></param>
        public virtual Uri UploadAttachment(UploadAttachment Attachment, Twitter.Account account)
        {
            if(string.IsNullOrEmpty(account.OAuth_token) || string.IsNullOrEmpty(account.OAuth_token_secret))
                throw new InvalidOperationException(Localization.XmlBasedResourceManager.GetString("No credentials supplied"));
            using (Stream contentStream = Attachment.GetStream())
            {
                if (contentStream == null)
                    throw new InvalidOperationException(Localization.XmlBasedResourceManager.GetString("Unable to open file"));

                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(API_UPLOAD);
                request.Timeout = 60000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("source", "PockeTwit");
                contents.Add("sourceLink", "http://code.google.com/p/pocketwit/");
                if (!string.IsNullOrEmpty(Attachment.Caption))
                    contents.Add("message", Attachment.Caption);

                contents.Add("media",
                    contentStream,
                    Path.GetFileName(Attachment.Name),
                    (Attachment.MediaType != null) ?
                        Attachment.MediaType.ContentType
                        : string.Empty
                );

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                XmlDocument uploadResult = contents.UploadXML(request);
                if (uploadResult == null)
                    throw new InvalidOperationException("Error parsing result");
                return new Uri(uploadResult.SelectSingleNode("//url").InnerText);
            }
        }
Exemplo n.º 48
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;
                request.Headers.Add("Action", "upload");

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("key", APPLICATION_NAME);

                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    contents.Add("message", ppo.Message);
                    string hashTags = FindHashTags(ppo.Message, ",", 32);
                    if (!string.IsNullOrEmpty(hashTags))
                    {
                        contents.Add("tags", hashTags);
                    }
                }
                else
                {
                    contents.Add("message", "");
                }

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Add("latlong", string.Format("{0},{1}", ppo.Lat, ppo.Lon));
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, _account.OAuth_token, _account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (WebException ex)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, API_ERROR_UPLOAD, String.Format("Received response {0} from server ({1})", ex.Status, ex.Message)));
                return null;
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 49
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("api_key", TwitrPixKey);

                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename));

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    contents.Add("latitude", ppo.Lat);
                    contents.Add("longitude", ppo.Lat);
                }

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (WebException we)
            {
                StreamReader sr = new StreamReader(we.Response.GetResponseStream());
                string resp = sr.ReadToEnd();
                Console.WriteLine(resp);
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.
                //Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 50
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);

                request.PreAuthenticate = true;
                request.AllowWriteStreamBuffering = false;
                request.Timeout = 60000;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename));

                OAuth.OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);
                return contents.UploadXML(request);
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 51
0
        /// <summary>
        /// Upload the picture
        /// </summary>
        /// <param name="url">URL to upload picture to</param>
        /// <param name="ppo">Postdata</param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);
                request.Timeout = 20000;
                request.AllowWriteStreamBuffering = false; // don't want to buffer 3MB files, thanks
                request.AllowAutoRedirect = false;

                Multipart contents = new Multipart();
                contents.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);
                contents.Add("api_key", API_KEY);
                contents.Add("source", API_ORIGIN_ID);
                if (!string.IsNullOrEmpty(ppo.Message))
                    contents.Add("message", ppo.Message);
                else
                    contents.Add("message", "");

                string contentType = "";
                foreach (MediaType ft in this.API_FILETYPES)
                {
                    if (ft.Extension.Equals(Path.GetExtension(ppo.Filename).Substring(1), StringComparison.InvariantCultureIgnoreCase))
                    {
                        contentType = ft.ContentType;
                        break;
                    }
                }

                contents.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), contentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret);

                return contents.UploadXML(request);
            }
            catch (Exception)
            {
                //Socket exception 10054 could occur when sending large files.
                // Should be more specific

                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, string.Empty, API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 52
0
		public void TestMultipartAlternative ()
		{
			var msg = new Multipart ("alternative",
				new TextPart ("plain", "Just a short message to say hello!"),
				new TextPart ("html", "<html><head></head><body><strong>Just a short message to say hello!</strong></body></html>")
			);

			Assert.AreEqual (2, msg.Count, "Parts count is wrong");
			Assert.AreEqual ("plain", msg[0].ContentType.MediaSubtype, "Parts[0] has wrong media subtype");
			Assert.AreEqual ("html", msg[1].ContentType.MediaSubtype, "Parts[1] has wrong media subtype");
			Assert.AreEqual ("Just a short message to say hello!", ((TextPart)msg[0]).Text, "Parts[0] containes wrong text");
			Assert.AreEqual ("<html><head></head><body><strong>Just a short message to say hello!</strong></body></html>", 
				((TextPart)msg[1]).Text, "Parts[1] containes wrong text");
		}
Exemplo n.º 53
0
		/// <summary>
		/// Creates a new <see cref="MimeMessage"/> from a <see cref="System.Net.Mail.MailMessage"/>.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="MimeMessage"/> from a <see cref="System.Net.Mail.MailMessage"/>.
		/// </remarks>
		/// <returns>The equivalent <see cref="MimeMessage"/>.</returns>
		/// <param name="message">The message.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="message"/> is <c>null</c>.
		/// </exception>
		public static MimeMessage CreateFromMailMessage (MailMessage message)
		{
			if (message == null)
				throw new ArgumentNullException ("message");

			var headers = new List<Header> ();
			foreach (var field in message.Headers.AllKeys) {
				foreach (var value in message.Headers.GetValues (field))
					headers.Add (new Header (field, value));
			}

			var msg = new MimeMessage (ParserOptions.Default, headers);
			MimeEntity body = null;

			// Note: If the user has already sent their MailMessage via System.Net.Mail.SmtpClient,
			// then the following MailMessage properties will have been merged into the Headers, so
			// check to make sure our MimeMessage properties are empty before adding them.
			if (msg.Sender == null && message.Sender != null)
				msg.Sender = (MailboxAddress) message.Sender;
			if (msg.From.Count == 0 && message.From != null)
				msg.From.Add ((MailboxAddress) message.From);
#if NET_3_5
			if (msg.ReplyTo.Count == 0 && message.ReplyTo != null)
				msg.ReplyTo.Add ((MailboxAddress) message.ReplyTo);
#else
			if (msg.ReplyTo.Count == 0 && message.ReplyToList.Count > 0)
				msg.ReplyTo.AddRange ((InternetAddressList) message.ReplyToList);
#endif
			if (msg.To.Count == 0 && message.To.Count > 0)
				msg.To.AddRange ((InternetAddressList) message.To);
			if (msg.Cc.Count == 0 && message.CC.Count > 0)
				msg.Cc.AddRange ((InternetAddressList) message.CC);
			if (msg.Bcc.Count == 0 && message.Bcc.Count > 0)
				msg.Bcc.AddRange ((InternetAddressList) message.Bcc);
			if (string.IsNullOrEmpty (msg.Subject))
				msg.Subject = message.Subject ?? string.Empty;

			switch (message.Priority) {
			case MailPriority.High:
				msg.Headers.Replace (HeaderId.Priority, "urgent");
				msg.Headers.Replace (HeaderId.Importance, "high");
				msg.Headers.Replace ("X-Priority", "1");
				break;
			case MailPriority.Low:
				msg.Headers.Replace (HeaderId.Priority, "non-urgent");
				msg.Headers.Replace (HeaderId.Importance, "low");
				msg.Headers.Replace ("X-Priority", "5");
				break;
			}

			if (!string.IsNullOrEmpty (message.Body)) {
				var text = new TextPart (message.IsBodyHtml ? "html" : "plain");
				text.SetText (message.BodyEncoding ?? Encoding.UTF8, message.Body);
				body = text;
			}

			if (message.AlternateViews.Count > 0) {
				var alternative = new Multipart ("alternative");

				if (body != null)
					alternative.Add (body);

				foreach (var view in message.AlternateViews) {
					var part = GetMimePart (view);

					if (view.BaseUri != null)
						part.ContentLocation = view.BaseUri;

					if (view.LinkedResources.Count > 0) {
						var type = part.ContentType.MediaType + "/" + part.ContentType.MediaSubtype;
						var related = new Multipart ("related");

						related.ContentType.Parameters.Add ("type", type);

						if (view.BaseUri != null)
							related.ContentLocation = view.BaseUri;

						related.Add (part);

						foreach (var resource in view.LinkedResources) {
							part = GetMimePart (resource);

							if (resource.ContentLink != null)
								part.ContentLocation = resource.ContentLink;

							related.Add (part);
						}

						alternative.Add (related);
					} else {
						alternative.Add (part);
					}
				}

				body = alternative;
			}

			if (body == null)
				body = new TextPart (message.IsBodyHtml ? "html" : "plain");

			if (message.Attachments.Count > 0) {
				var mixed = new Multipart ("mixed");

				if (body != null)
					mixed.Add (body);

				foreach (var attachment in message.Attachments)
					mixed.Add (GetMimePart (attachment));

				body = mixed;
			}

			msg.Body = body;

			return msg;
		}
Exemplo n.º 54
0
        unsafe BoundaryType MultipartScanSubparts(Multipart multipart, byte* inbuf)
        {
            BoundaryType found;

            do {
                // skip over the boundary marker
                if (!SkipLine (inbuf))
                    return BoundaryType.Eos;

                // parse the headers
                state = MimeParserState.Headers;
                if (Step (inbuf) == MimeParserState.Error)
                    return BoundaryType.Eos;

                //if (state == ParserState.Complete && headers.Count == 0)
                //	return BoundaryType.EndBoundary;

                var type = GetContentType (multipart.ContentType);
                var entity = MimeEntity.Create (options, type, headers, false);

                if (entity is Multipart)
                    found = ConstructMultipart ((Multipart) entity, inbuf);
                else if (entity is MessagePart)
                    found = ConstructMessagePart ((MessagePart) entity, inbuf);
                else
                    found = ConstructMimePart ((MimePart) entity, inbuf);

                multipart.Add (entity);
            } while (found == BoundaryType.ImmediateBoundary);

            return found;
        }
Exemplo n.º 55
0
		/// <summary>
		/// Visit the children of a <see cref="MimeKit.Multipart"/>.
		/// </summary>
		/// <remarks>
		/// Visits the children of a <see cref="MimeKit.Multipart"/>.
		/// </remarks>
		/// <param name="multipart">Multipart.</param>
		protected virtual void VisitChildren (Multipart multipart)
		{
			for (int i = 0; i < multipart.Count; i++)
				multipart[i].Accept (this);
		}
Exemplo n.º 56
0
			protected override void VisitMultipart (Multipart multipart)
			{
				if (multipart.ContentType.Matches ("multipart", "signed")) {
					// do not modify children of a multipart/signed
					return;
				}

				base.VisitMultipart (multipart);
			}
Exemplo n.º 57
0
        /// <summary>
        /// Upload a picture
        /// </summary>
        /// <param name="url"></param>
        /// <param name="ppo"></param>
        /// <returns></returns>
        private XmlDocument UploadPicture(string url, PicturePostObject ppo, Twitter.Account account)
        {
            try
            {
                HttpWebRequest request = WebRequestFactory.CreateHttpRequest(url);

                string boundary = System.Guid.NewGuid().ToString();
                request.Timeout = 20000;
                request.AllowAutoRedirect = false;
                request.AllowWriteStreamBuffering = false;
                request.PreAuthenticate = true;

                Multipart content = new Multipart();
                content.UploadPart += new Multipart.UploadPartEvent(contents_UploadPart);

                content.Add("source", "pocketwit");

                if (!string.IsNullOrEmpty(ppo.Lat) && !string.IsNullOrEmpty(ppo.Lon))
                {
                    string geotag = string.Format("geotagged,geo:lat={0},geo:lon={1}", ppo.Lat, ppo.Lon);
                    content.Add("tags", geotag);
                }

                if (!string.IsNullOrEmpty(ppo.Message))
                {
                    content.Add("message", ppo.Message);
                }

                content.Add("media", ppo.PictureStream, Path.GetFileName(ppo.Filename), ppo.ContentType);

                OAuthAuthorizer.AuthorizeEcho(request, account.OAuth_token, account.OAuth_token_secret, Twitter.OutputFormatType.XML);

                return content.UploadXML(request);
            }
            catch (Exception)
            {
                OnErrorOccured(new PictureServiceEventArgs(PictureServiceErrorLevel.Failed, "", API_ERROR_UPLOAD));
                return null;
            }
        }
Exemplo n.º 58
0
		/// <summary>
		/// Creates a new <see cref="MimeMessage"/> from a <see cref="System.Net.Mail.MailMessage"/>.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="MimeMessage"/> from a <see cref="System.Net.Mail.MailMessage"/>.
		/// </remarks>
		/// <returns>The equivalent <see cref="MimeMessage"/>.</returns>
		/// <param name="message">The message.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="message"/> is <c>null</c>.
		/// </exception>
		public static MimeMessage CreateFromMailMessage (MailMessage message)
		{
			if (message == null)
				throw new ArgumentNullException ("message");

			var headers = new List<Header> ();
			foreach (var field in message.Headers.AllKeys) {
				foreach (var value in message.Headers.GetValues (field))
					headers.Add (new Header (field, value));
			}

			var msg = new MimeMessage (ParserOptions.Default, headers);
			MimeEntity body = null;

			if (message.Sender != null)
				msg.Sender = (MailboxAddress) message.Sender;
			if (message.From != null)
				msg.From.Add ((MailboxAddress) message.From);
			msg.ReplyTo.AddRange ((InternetAddressList) message.ReplyToList);
			msg.To.AddRange ((InternetAddressList) message.To);
			msg.Cc.AddRange ((InternetAddressList) message.CC);
			msg.Bcc.AddRange ((InternetAddressList) message.Bcc);
			msg.Subject = message.Subject ?? string.Empty;

			switch (message.Priority) {
			case MailPriority.High:
				msg.Headers.Add (HeaderId.Priority, "urgent");
				msg.Headers.Add (HeaderId.Importance, "high");
				msg.Headers.Add ("X-Priority", "1");
				break;
			case MailPriority.Low:
				msg.Headers.Add (HeaderId.Priority, "non-urgent");
				msg.Headers.Add (HeaderId.Importance, "low");
				msg.Headers.Add ("X-Priority", "5");
				break;
			}

			if (message.Body != null) {
				var text = new TextPart (message.IsBodyHtml ? "html" : "plain");
				text.SetText (message.BodyEncoding ?? Encoding.UTF8, message.Body);
				body = text;
			}

			if (message.AlternateViews.Count > 0) {
				var alternative = new Multipart ("alternative");

				if (body != null)
					alternative.Add (body);

				foreach (var view in message.AlternateViews) {
					var part = GetMimePart (view);

					if (view.BaseUri != null)
						part.ContentLocation = view.BaseUri;

					if (view.LinkedResources.Count > 0) {
						var type = part.ContentType.MediaType + "/" + part.ContentType.MediaSubtype;
						var related = new Multipart ("related");

						related.ContentType.Parameters.Add ("type", type);

						if (view.BaseUri != null)
							related.ContentLocation = view.BaseUri;

						related.Add (part);

						foreach (var resource in view.LinkedResources) {
							part = GetMimePart (resource);

							if (resource.ContentLink != null)
								part.ContentLocation = resource.ContentLink;

							related.Add (part);
						}

						alternative.Add (related);
					} else {
						alternative.Add (part);
					}
				}

				body = alternative;
			}

			if (message.Attachments.Count > 0) {
				var mixed = new Multipart ("mixed");

				if (body != null)
					mixed.Add (body);

				foreach (var attachment in message.Attachments)
					mixed.Add (GetMimePart (attachment));

				body = mixed;
			}

			msg.Body = body;

			return msg;
		}