static MessagePart CreateImapExampleInnerMessageRfc822(List <MimeEntity> parents)
        {
            var message     = new MimeMessage();
            var mixed       = new Multipart("mixed");
            var alternative = new MultipartAlternative();
            var rfc822      = new MessagePart {
                Message = message
            };

            parents.Add(rfc822);
            message.Body = mixed;

            parents.Add(mixed);
            mixed.Add(new TextPart("plain"));

            parents.Add(mixed);
            mixed.Add(alternative);

            parents.Add(alternative);
            alternative.Add(new TextPart("plain"));

            parents.Add(alternative);
            alternative.Add(new TextPart("richtext"));

            return(rfc822);
        }
        private static MimeEntity AppendAlternativeViews(MailMessage mail, MimeEntity originalBody)
        {
            if (mail.AlternateViews.Count == 0)
            {
                return(null);
            }

            var body = new MultipartAlternative();

            if (originalBody != null)
            {
                body.Add(originalBody);
            }

            foreach (var alternativeView in mail.AlternateViews)
            {
                var part = GetMimePart(alternativeView);
                if (alternativeView.BaseUri != null)
                {
                    part.ContentLocation = alternativeView.BaseUri;
                }

                // Determine if the alternative view have linked resources
                if (alternativeView.LinkedResources.Count == 0)
                {
                    body.Add(part);
                    continue;
                }

                // Create a multipart relation
                var type    = part.ContentType.MediaType + "/" + part.ContentType.MediaSubtype;
                var related = new MultipartRelated();

                related.ContentType.Parameters.Add("type", type);
                if (alternativeView.BaseUri != null)
                {
                    related.ContentLocation = alternativeView.BaseUri;
                }

                related.Add(part);

                // Add all the linked resources to the relation
                foreach (var resource in alternativeView.LinkedResources)
                {
                    part = GetMimePart(resource);
                    if (resource.ContentLink != null)
                    {
                        part.ContentLocation = resource.ContentLink;
                    }

                    related.Add(part);
                }

                // Append the linked resource to the alternative view
                body.Add(related);
            }

            return(body);
        }
        /// <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);
        }
Beispiel #4
0
        public Task <IMimeMessage> CreateInstance(IEnumerable <MimeHeader> headers,
                                                  IEnumerable <MimeEntity> bodyParts,
                                                  IEnumerable <MimeEntity> attachments)
        {
            var message = new global::MimeKit.MimeMessage();

            message.Headers.Clear();

            foreach (var header in headers)
            {
                message.Headers.Add(header.Field, header.Value);
            }

            var multipartMixed       = new Multipart("mixed");
            var multipartAlternative = new MultipartAlternative();

            foreach (var bodyPart in bodyParts)
            {
                multipartAlternative.Add(CreateMimePart <TextPart>(bodyPart));
            }

            multipartMixed.Add(multipartAlternative);

            foreach (var attachment in attachments)
            {
                multipartMixed.Add(CreateMimePart <MimePart>(attachment));
            }

            message.Body = multipartMixed;

            return(Task.FromResult((IMimeMessage) new MimeMessage(message)));
        }
Beispiel #5
0
        public void CreateMessage()
        {
            var textpart   = CreateTextPart();
            var htmlpart   = CreateHtmlPart();
            var attachment = CreateAttachment(@"F:\source_files\smtp_client\Invoice#IN19103288.pdf");

            var alternative = new MultipartAlternative();

            alternative.Add(textpart);
            alternative.Add(htmlpart);

            var multipart = new Multipart("mixed");

            multipart.Add(alternative);
            multipart.Add(attachment);

            mimeMessage.Body = multipart;
        }
Beispiel #6
0
        public void TestGetTextBodyAlternativeInsideRelated()
        {
            var alternative = new MultipartAlternative();
            var plain       = new TextPart("plain")
            {
                Text = "plain\n"
            };
            var flowed = new TextPart(TextFormat.Flowed)
            {
                Text = "flowed\n"
            };
            var richtext = new TextPart("rtf")
            {
                Text = "rtf\n"
            };
            var html = new TextPart("html")
            {
                Text = "html\n"
            };

            alternative.Add(plain);
            alternative.Add(richtext);
            alternative.Add(html);

            var related = new MultipartRelated();

            related.Add(alternative);

            var outer = new MultipartAlternative();

            outer.Add(related);

            Assert.AreEqual("plain\n", outer.TextBody.Replace("\r\n", "\n"), "TextBody");
            Assert.AreEqual("html\n", outer.HtmlBody.Replace("\r\n", "\n"), "HtmlBody");

            alternative.Insert(1, flowed);

            // Note: GetTextBody (Plain) returns Flowed because Flowed is also Plain and is listed after the text/plain part
            Assert.AreEqual("flowed\n", outer.GetTextBody(TextFormat.Plain).Replace("\r\n", "\n"), "Plain");
            Assert.AreEqual("flowed\n", outer.GetTextBody(TextFormat.Flowed).Replace("\r\n", "\n"), "Flowed");
            Assert.AreEqual("rtf\n", outer.GetTextBody(TextFormat.RichText).Replace("\r\n", "\n"), "RichText");
            Assert.AreEqual("html\n", outer.GetTextBody(TextFormat.Html).Replace("\r\n", "\n"), "Html");
            Assert.IsNull(outer.GetTextBody(TextFormat.Enriched), "Enriched");
        }
Beispiel #7
0
        public void CreateMessage(string textpart, string htmlpart, string attachments)
        {
            var _textpart = CreateTextPart(textpart);
            var _htmlpart = CreateHtmlPart(htmlpart);
            //var attachment = CreateAttachment(mailpartsFolder + "\\annotate.pdf");
            var attachment = CreateAttachment(attachments);

            var alternative = new MultipartAlternative();

            alternative.Add(_textpart);
            alternative.Add(_htmlpart);

            var multipart = new Multipart("mixed");

            multipart.Add(alternative);
            multipart.Add(attachment);

            mimeMessage.Body = multipart;
        }
        public static MimeMessage ToMimeMessage(this MailMessage mail)
        {
            if (mail == null)
            {
                throw new ArgumentNullException(nameof(mail));
            }

            var headers = new List <Header>();

            foreach (var field in mail.Headers.AllKeys)
            {
                foreach (var value in mail.Headers.GetValues(field))
                {
                    headers.Add(new Header(field, value));
                }
            }

            var        message = new MimeMessage(headers.ToArray());
            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 (mail.Sender != null)
            {
                message.Sender = mail.Sender.ToMailboxAddress();
            }

            if (mail.From != null)
            {
                message.Headers.Replace(HeaderId.From, string.Empty);
                message.From.Add(mail.From.ToMailboxAddress());
            }

            if (mail.ReplyToList.Count > 0)
            {
                message.Headers.Replace(HeaderId.ReplyTo, string.Empty);
                message.ReplyTo.AddRange(mail.ReplyToList.ToInternetAddressList());
            }

            if (mail.To.Count > 0)
            {
                message.Headers.Replace(HeaderId.To, string.Empty);
                message.To.AddRange(mail.To.ToInternetAddressList());
            }

            if (mail.CC.Count > 0)
            {
                message.Headers.Replace(HeaderId.Cc, string.Empty);
                message.Cc.AddRange(mail.CC.ToInternetAddressList());
            }

            if (mail.Bcc.Count > 0)
            {
                message.Headers.Replace(HeaderId.Bcc, string.Empty);
                message.Bcc.AddRange(mail.Bcc.ToInternetAddressList());
            }

            if (mail.SubjectEncoding != null)
            {
                message.Headers.Replace(HeaderId.Subject, mail.SubjectEncoding, mail.Subject ?? string.Empty);
            }
            else
            {
                message.Subject = mail.Subject ?? string.Empty;
            }

            switch (mail.Priority)
            {
            case MailPriority.Normal:
                message.Headers.RemoveAll(HeaderId.XMSMailPriority);
                message.Headers.RemoveAll(HeaderId.Importance);
                message.Headers.RemoveAll(HeaderId.XPriority);
                message.Headers.RemoveAll(HeaderId.Priority);
                break;

            case MailPriority.High:
                message.Headers.Replace(HeaderId.Priority, "urgent");
                message.Headers.Replace(HeaderId.Importance, "high");
                message.Headers.Replace(HeaderId.XPriority, "2 (High)");
                break;

            case MailPriority.Low:
                message.Headers.Replace(HeaderId.Priority, "non-urgent");
                message.Headers.Replace(HeaderId.Importance, "low");
                message.Headers.Replace(HeaderId.XPriority, "4 (Low)");
                break;
            }

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

            if (mail.AlternateViews.Count > 0)
            {
                var alternative = new MultipartAlternative();

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

                foreach (var view in mail.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 MultipartRelated();

                        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(mail.IsBodyHtml ? "html" : "plain");
            }

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

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

                foreach (var attachment in mail.Attachments)
                {
                    mixed.Add(GetMimePart(attachment));
                }

                body = mixed;
            }

            message.Body = body;

            return(message);
        }
Beispiel #9
0
        private MimeMessage BuildMailMessage(NotifyMessage m)
        {
            var mimeMessage = new MimeMessage
            {
                Subject = m.Subject
            };

            var fromAddress = MailboxAddress.Parse(ParserOptions.Default, m.From);

            mimeMessage.From.Add(fromAddress);

            foreach (var to in m.To.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
            {
                mimeMessage.To.Add(MailboxAddress.Parse(ParserOptions.Default, to));
            }

            if (m.ContentType == Pattern.HTMLContentType)
            {
                var textPart = new TextPart("plain")
                {
                    Text = HtmlUtil.GetText(m.Content),
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                var multipartAlternative = new MultipartAlternative {
                    textPart
                };

                var htmlPart = new TextPart("html")
                {
                    Text = GetHtmlView(m.Content),
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };

                if (m.EmbeddedAttachments != null && m.EmbeddedAttachments.Length > 0)
                {
                    var multipartRelated = new MultipartRelated
                    {
                        Root = htmlPart
                    };

                    foreach (var attachment in m.EmbeddedAttachments)
                    {
                        var mimeEntity = ConvertAttachmentToMimePart(attachment);
                        if (mimeEntity != null)
                        {
                            multipartRelated.Add(mimeEntity);
                        }
                    }

                    multipartAlternative.Add(multipartRelated);
                }
                else
                {
                    multipartAlternative.Add(htmlPart);
                }

                mimeMessage.Body = multipartAlternative;
            }
            else
            {
                mimeMessage.Body = new TextPart("plain")
                {
                    Text = m.Content,
                    ContentTransferEncoding = ContentEncoding.QuotedPrintable
                };
            }

            if (!string.IsNullOrEmpty(m.ReplyTo))
            {
                mimeMessage.ReplyTo.Add(MailboxAddress.Parse(ParserOptions.Default, m.ReplyTo));
            }

            mimeMessage.Headers.Add("Auto-Submitted", string.IsNullOrEmpty(m.AutoSubmitted) ? "auto-generated" : m.AutoSubmitted);

            return(mimeMessage);
        }
Beispiel #10
0
        /// <summary>
        /// Sends an email via SMTP, based on the provided settings.
        /// </summary>
        /// <param name="senderName">The name of the person sending the email.</param>
        /// <param name="senderAddress">The email address of the person sending the email.</param>
        /// <param name="recipients">An enumeration of recipients who will receive the email.</param>
        /// <param name="subject">The subject line of the email.</param>
        /// <param name="htmlContent">The HTML content of the email.</param>
        /// <param name="textContent">The text content of the email.</param>
        /// <param name="attachments">Attachments to send with the email.</param>
        /// <param name="settings">The settings to be used when sending the email.</param>
        /// <returns>An instance of <see cref="EmailResult"/> indicating success/failure.</returns>
        /// <example>
        /// <code>
        /// using Cake.Email.Common;
        ///
        /// var smtpHost = "... your smtp host ...";
        /// var port = 1234;
        /// var enableSsl = true;
        /// var username = "******";
        /// var password = "******";
        /// var attachments = new[]
        /// {
        ///     Attachment.FromLocalFile("C:\\temp\\MyFile.txt"),
        ///     Attachment.FromLocalFile("C:\\temp\\MySpreadsheet.xls"),
        ///     Attachment.FromLocalFile("C:\\temp\\MyFile.pdf")
        /// };
        /// try
        /// {
        ///     var result = Email.SendEmail(
        ///         senderName: "Bob Smith",
        ///         senderAddress: "*****@*****.**",
        ///         recipients: new[]
        ///         {
        ///             new MailAddress("*****@*****.**", "Jane Doe"),
        ///             new MailAddress("*****@*****.**", "Bob Smith"),
        ///         },
        ///         subject: "This is a test",
        ///         htmlContent: "<html><body>This is a test</body></html>",
        ///         textContent: "This is the text only version of this email",
        ///         attachments: attachments,
        ///         settings: new EmailSettings
        ///         {
        ///             SmtpHost = smtpHost,
        ///             Port = port,
        ///             EnableSsl = enableSsl,
        ///             Username = username,
        ///             Password = password
        ///         }
        ///     );
        ///     if (result.Ok)
        ///     {
        ///         Information("Email succcessfully sent");
        ///     }
        ///     else
        ///     {
        ///         Error("Failed to send email: {0}", result.Error);
        ///     }
        /// }
        /// catch(Exception ex)
        /// {
        ///     Error("{0}", ex);
        /// }
        /// </code>
        /// </example>
        public EmailResult SendEmail(string senderName, string senderAddress, IEnumerable <MailAddress> recipients, string subject, string htmlContent, string textContent, IEnumerable <Attachment> attachments, EmailSettings settings)
        {
            try
            {
                if (recipients == null || !recipients.Any(r => r != null))
                {
                    throw new CakeException("You must specify at least one recipient");
                }

                var safeRecipients = recipients.Where(r => r != null && !string.IsNullOrEmpty(r.Address));
                if (!safeRecipients.Any())
                {
                    throw new CakeException("None of the recipients you specified have an email address");
                }

                if (attachments == null)
                {
                    attachments = Enumerable.Empty <Attachment>();
                }

                using (var client = new SmtpClient())
                {
                    _context.Log.Verbose("Sending email to {0} via SMTP...", string.Join(", ", safeRecipients.Select(r => r.Address).ToArray()));

                    client.Connect(settings.SmtpHost, settings.Port, settings.EnableSsl);

                    if (!string.IsNullOrEmpty(settings.Username))
                    {
                        client.Authenticate(settings.Username, settings.Password);
                    }

                    var from = new MailboxAddress(senderName, senderAddress);

                    var message = new MimeMessage();
                    message.From.Add(from);
                    message.Subject = subject;

                    foreach (var recipient in safeRecipients)
                    {
                        message.To.Add(new MailboxAddress(recipient.Name, recipient.Address));
                    }

                    /*
                     * IMPORTANT: the order of body parts is significant.
                     * Parts in a multipart MIME message should be in order of increasing preference
                     * See: https://www.ietf.org/rfc/rfc1521.txt (section 7.2.3)
                     */
                    var content = new MultipartAlternative();

                    if (!string.IsNullOrEmpty(textContent))
                    {
                        content.Add(new TextPart("plain")
                        {
                            Text = textContent
                        });
                    }

                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        content.Add(new TextPart("html")
                        {
                            Text = htmlContent
                        });
                    }

                    var multipart = new Multipart("mixed")
                    {
                        content
                    };

                    foreach (var attachment in attachments)
                    {
                        var disposition = string.IsNullOrEmpty(attachment.ContentId) ? ContentDisposition.Attachment : ContentDisposition.Inline;
                        multipart.Add(new MimePart(attachment.MimeType)
                        {
                            ContentId               = attachment.ContentId,
                            Content                 = new MimeContent(attachment.ContentStream, ContentEncoding.Default),
                            ContentDisposition      = new ContentDisposition(disposition),
                            ContentTransferEncoding = ContentEncoding.Base64,
                            FileName                = attachment.Name
                        });
                    }

                    message.Body = multipart;

                    client.Send(message);

                    client.Disconnect(true);
                }

                return(new EmailResult(true, DateTime.UtcNow.ToString("u"), string.Empty));
            }
            catch (Exception e)
            {
                while (e.InnerException != null)
                {
                    e = e.InnerException;
                }

                if (settings.ThrowOnFail.HasValue && settings.ThrowOnFail.Value)
                {
                    throw new CakeException(e.Message);
                }
                else
                {
                    return(new EmailResult(false, DateTime.UtcNow.ToString("u"), e.Message));
                }
            }
        }