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); }
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))); }
public void TestArgumentExceptions() { var alternative = new MultipartAlternative(); Assert.Throws <ArgumentNullException> (() => new MultipartAlternative((MimeEntityConstructorArgs)null)); Assert.Throws <ArgumentNullException> (() => alternative.Accept(null)); }
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); }
protected override void VisitMultipartAlternative(MultipartAlternative alternative) { // walk the multipart/alternative children backwards from greatest level of faithfulness to the least faithful for (int i = alternative.Count - 1; i >= 0 && body == null; i--) { alternative[i].Accept(this); } }
/// <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); }
protected override void VisitMultipartAlternative(MultipartAlternative alternative) { var multipart = new MultipartAlternative(); Push(multipart); for (int i = 0; i < alternative.Count; i++) { alternative[i].Accept(this); } Pop(); }
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; }
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"); }
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; }
/// <summary> /// 组装邮件文本/附件邮件信息 /// </summary> /// <param name="mailBodyEntity">邮件消息实体</param> /// <returns></returns> public static MimeMessage AssemblyMailMessage(MailBodyEntity mailBodyEntity) { if (mailBodyEntity == null) { throw new ArgumentNullException(nameof(mailBodyEntity)); } var message = new MimeMessage(); //设置邮件基本信息 SetMailBaseMessage(message, mailBodyEntity); var multipart = new Multipart("mixed"); //插入文本消息 if (!string.IsNullOrEmpty(mailBodyEntity.Body)) { var alternative = new MultipartAlternative { AssemblyMailTextMessage(mailBodyEntity.Body, mailBodyEntity.MailBodyType) }; multipart.Add(alternative); } if (mailBodyEntity.MailFiles != null) { //插入附件 foreach (var mailFile in mailBodyEntity.MailFiles) { if (mailFile.MailFilePath != null && File.Exists(mailFile.MailFilePath)) { var mimePart = AssemblyMailAttachmentMessage(mailFile.MailFileType, mailFile.MailFileSubType, mailFile.MailFilePath); multipart.Add(mimePart); } } } //组合邮件内容 message.Body = multipart; return(message); }
private MultipartAlternative GetMultipartAlternativeFromBody(BodyBuilder body) { //Sets body content encooding to quoated-printable to avoid rejection by NHS email servers var htmlPart = new TextPart(TextFormat.Html) { ContentTransferEncoding = ContentEncoding.QuotedPrintable }; htmlPart.SetText(Encoding.UTF8, body.HtmlBody); var textPart = new TextPart(TextFormat.Plain) { ContentTransferEncoding = ContentEncoding.QuotedPrintable }; textPart.SetText(Encoding.UTF8, body.TextBody); var multipartAlternative = new MultipartAlternative { textPart, htmlPart }; return(multipartAlternative); }
public async Task SendEmailAsync(string toAddress, string subject, string html, string alternative) { MimeMessage email = new MimeMessage(); email.From.Add(new MailboxAddress(_options.FromAddress.Name, _options.FromAddress.Address)); email.To.Add(new MailboxAddress(string.Empty, toAddress)); email.Subject = subject; MultipartAlternative body = new MultipartAlternative { new TextPart("html") { Text = html }, new TextPart("plain") { Text = alternative } }; email.Body = body; await SendEmailAsync(email); }
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); }
/// <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)); } } }
private static MimeEntity ToMimeMessageBody(MailDraftData draft) { string textBody; MailUtil.TryExtractTextFromHtml(draft.HtmlBody, out textBody); MultipartAlternative alternative = null; MimeEntity body = null; if (!string.IsNullOrEmpty(textBody)) { var textPart = new TextPart("plain") { Text = textBody, ContentTransferEncoding = ContentEncoding.QuotedPrintable }; if (!string.IsNullOrEmpty(draft.HtmlBody)) { alternative = new MultipartAlternative { textPart }; body = alternative; } else { body = textPart; } } if (!string.IsNullOrEmpty(draft.HtmlBody)) { var htmlPart = new TextPart("html") { Text = draft.HtmlBody, ContentTransferEncoding = ContentEncoding.QuotedPrintable }; MimeEntity html; if (draft.AttachmentsEmbedded.Any()) { htmlPart.ContentTransferEncoding = ContentEncoding.Base64; var related = new MultipartRelated { Root = htmlPart }; related.Root.ContentId = null; foreach (var emb in draft.AttachmentsEmbedded) { var linkedResource = ConvertToMimePart(emb, emb.contentId); related.Add(linkedResource); } html = related; } else { html = htmlPart; } if (alternative != null) { alternative.Add(html); } else { body = html; } } if (!string.IsNullOrEmpty(draft.CalendarIcs)) { var calendarPart = new TextPart("calendar") { Text = draft.CalendarIcs, ContentTransferEncoding = ContentEncoding.QuotedPrintable }; calendarPart.ContentType.Parameters.Add("method", draft.CalendarMethod); if (alternative != null) { alternative.Add(calendarPart); } else { body = calendarPart; } } if (draft.Attachments.Any() || !string.IsNullOrEmpty(draft.CalendarIcs)) { var mixed = new Multipart("mixed"); if (body != null) { mixed.Add(body); } foreach (var att in draft.Attachments) { var attachment = ConvertToMimePart(att); mixed.Add(attachment); } if (!string.IsNullOrEmpty(draft.CalendarIcs)) { var filename = "calendar.ics"; switch (draft.CalendarMethod) { case Defines.ICAL_REQUEST: filename = "invite.ics"; break; case Defines.ICAL_REPLY: filename = "reply.ics"; break; case Defines.ICAL_CANCEL: filename = "cancel.ics"; break; } var contentType = new ContentType("application", "ics"); contentType.Parameters.Add("method", draft.CalendarMethod); contentType.Parameters.Add("name", filename); var calendarResource = new MimePart(contentType) { ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, FileName = filename }; var data = Encoding.UTF8.GetBytes(draft.CalendarIcs); var ms = new MemoryStream(data); calendarResource.Content = new MimeContent(ms); mixed.Add(calendarResource); } body = mixed; } if (body != null) { return(body); } return(new TextPart("plain") { Text = string.Empty }); }
protected internal override void VisitMultipartAlternative(MultipartAlternative alternative) { MultipartAlternative++; base.VisitMultipartAlternative(alternative); }
/// <summary> /// Prepares the mail message part (plain text and/or HTML: /// Replacing placeholders with their values and setting correct encoding. /// </summary> private void BuildTextMessagePart(object dataIteam) { _badInlineFiles.Clear(); _textMessagePart = null; MultipartAlternative alternative = null; // create the plain text body part TextPart plainTextPart = null; if (!string.IsNullOrEmpty(PlainText)) { var plainText = SearchAndReplaceVars(PlainText, dataIteam); plainTextPart = (TextPart) new PlainBodyBuilder(plainText) { TextTransferEncoding = Config.TextTransferEncoding, CharacterEncoding = Config.CharacterEncoding }.GetBodyPart(); if (!string.IsNullOrEmpty(HtmlText)) { // there is plain text AND html text alternative = new MultipartAlternative { plainTextPart }; _textMessagePart = alternative; } else { // there is only a plain text part, which could even be null _textMessagePart = plainTextPart; } } if (!string.IsNullOrEmpty(HtmlText)) { // create the HTML text body part with any linked resources // replacing any placeholders in the text or files with variable values var htmlBody = new HtmlBodyBuilder(this, dataIteam) { DocBaseUrl = Config.FileBaseDirectory, TextTransferEncoding = Config.TextTransferEncoding, BinaryTransferEncoding = Config.BinaryTransferEncoding, CharacterEncoding = Config.CharacterEncoding }; _inlineAttExternal.ForEach(ia => htmlBody.InlineAtt.Add(ia)); InlineAttachments = htmlBody.InlineAtt; htmlBody.BadInlineFiles.ToList().ForEach(f => _badInlineFiles.Add(f)); if (alternative != null) { alternative.Add(htmlBody.GetBodyPart()); _textMessagePart = alternative; } else { _textMessagePart = htmlBody.GetBodyPart(); } } else { InlineAttachments = new HashSet <FileAttachment>(); _badInlineFiles = new HashSet <string>(); } }
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); }
private static MimeEntity ToMimeMessageBody(MailDraft draft) { var linkedResources = new AttachmentCollection(true); var attachments = new AttachmentCollection(); string textBody; MailUtil.TryExtractTextFromHtml(draft.HtmlBody, out textBody); MultipartAlternative multipartAlternative = null; MimeEntity body = null; if (!string.IsNullOrEmpty(textBody)) { var textPart = new TextPart("plain") { Text = textBody, ContentTransferEncoding = ContentEncoding.QuotedPrintable }; if (!string.IsNullOrEmpty(draft.HtmlBody)) { multipartAlternative = new MultipartAlternative { textPart }; body = multipartAlternative; } else { body = textPart; } } if (!string.IsNullOrEmpty(draft.HtmlBody)) { var htmlPart = new TextPart("html") { Text = draft.HtmlBody, ContentTransferEncoding = ContentEncoding.QuotedPrintable }; MimeEntity tempPart; if (draft.AttachmentsEmbedded.Any()) { var multipartRelated = new MultipartRelated { Root = htmlPart }; foreach (var emb in draft.AttachmentsEmbedded) { MimeEntity linkedResource; if (!emb.data.Any()) { var s3Key = MailStoragePathCombiner.GerStoredFilePath(emb); var contentType = ContentType.Parse(string.IsNullOrEmpty(emb.contentType) ? MimeMapping.GetMimeMapping(emb.fileName) : emb.contentType); using (var stream = StorageManager .GetDataStoreForAttachments(emb.tenant) .GetReadStream(s3Key)) { linkedResource = linkedResources.Add(emb.fileName, stream, contentType); } } else { linkedResource = linkedResources.Add(emb.fileName, emb.data); } linkedResource.ContentId = emb.contentId; multipartRelated.Add(linkedResource); } tempPart = multipartRelated; } else { tempPart = htmlPart; } if (multipartAlternative != null) { multipartAlternative.Add(tempPart); } else { body = tempPart; } } if (!string.IsNullOrEmpty(draft.CalendarIcs)) { var calendarPart = new TextPart("calendar") { Text = draft.CalendarIcs, ContentTransferEncoding = ContentEncoding.QuotedPrintable }; calendarPart.ContentType.Parameters.Add("method", draft.CalendarMethod); if (multipartAlternative != null) { multipartAlternative.Add(calendarPart); } else { body = calendarPart; } } if (draft.Attachments.Any() || !string.IsNullOrEmpty(draft.CalendarIcs)) { var multipart = new Multipart("mixed"); if (body != null) { multipart.Add(body); } foreach (var att in draft.Attachments) { MimeEntity attachmentResource; if (!att.data.Any()) { var s3Key = MailStoragePathCombiner.GerStoredFilePath(att); using (var stream = StorageManager .GetDataStoreForAttachments(att.tenant) .GetReadStream(s3Key)) { attachmentResource = attachments.Add(att.fileName, stream); } } else { attachmentResource = attachments.Add(att.fileName, att.data); } multipart.Add(attachmentResource); } if (!string.IsNullOrEmpty(draft.CalendarIcs)) { var filename = "calendar.ics"; switch (draft.CalendarMethod) { case "REQUEST": filename = "invite.ics"; break; case "REPLY": filename = "reply.ics"; break; case "CANCEL": filename = "cancel.ics"; break; } var contentType = new ContentType("application", "ics"); contentType.Parameters.Add("method", draft.CalendarMethod); contentType.Parameters.Add("name", filename); var data = Encoding.UTF8.GetBytes(draft.CalendarIcs); var calendarResource = attachments.Add(filename, data, contentType); multipart.Add(calendarResource); } body = multipart; } if (body != null) { return(body); } return(new TextPart("plain") { Text = string.Empty }); }