myesn

myEsn2E9

hi
github

ABP: MailKit Attachment Chinese Name Garbled

Chinese garbled text:
image

After modification:
image
But after clicking preview, it is still garbled (not sure how to solve it) The latest code below has solved the garbled problem:
image

Originally, this was to modify the attachment parameters of MailKit, but ABP has encapsulated everything, so this article is somewhat related to ABP, and in terms of article classification, it belongs to ABP.

using MiaoXin.BackgroundJobs;
using MiaoXin.Utils;
using Microsoft.Extensions.Options;
using MimeKit;
using MimeKit.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.Emailing;
using Volo.Abp.Emailing.Smtp;
using Volo.Abp.MailKit;
using Volo.Abp.MultiTenancy;

namespace ?
{
    /// <summary>
    /// Override MailKitSmtpEmailSender to solve the problem of garbled Chinese attachment names
    /// </summary>
    public class ?MailKitSmtpEmailSender : MailKitSmtpEmailSender
    {
        public ?MailKitSmtpEmailSender(
            ISmtpEmailSenderConfiguration smtpConfiguration,
            IBackgroundJobManager backgroundJobManager,
            IOptions<AbpMailKitOptions> abpMailKitConfiguration)
            : base(smtpConfiguration, backgroundJobManager, abpMailKitConfiguration)
        {
        }

        protected override async Task SendEmailAsync(MailMessage mail)
        {
            // Default behavior, Chinese attachment names appear garbled in QQ mail
            /*return base.SendEmailAsync(mail)*/;

            using (var client = await BuildClientAsync())
            {
                //var message = MimeMessage.CreateFromMailMessage(mail);
                var message = BuildMimeMessageFromMailMessage(mail);
                message.MessageId = MimeUtils.GenerateMessageId();

                await client.SendAsync(message);
                await client.DisconnectAsync(true);
            }
        }

        private MimeMessage BuildMimeMessageFromMailMessage(MailMessage mailMessage)
        {
            var from = mailMessage.From;
            var to = mailMessage.To.First();

            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(from.DisplayName, from.Address));
            message.To.Add(new MailboxAddress(to.DisplayName, to.Address));
            message.Subject = mailMessage.Subject;
            
            var body = new TextPart(mailMessage.IsBodyHtml ? "html" : "plain")
            {
                Text =  mailMessage.Body
            };

            if(mailMessage.Attachments is not null && mailMessage.Attachments.Count > 0)
            {
                // now create the multipart/mixed container to hold the message text and the
                // image attachment
                var multipart = new Multipart("mixed")
                {
                    body,
                    //attachment
                };

                foreach (var attachment in mailMessage.Attachments)
                {
                    // create an image attachment for the file located at path
                    var attachmentMimePart = new MimePart(attachment.ContentType.MediaType)//"image", "jpg"
                    {
                        Content = new MimeContent(attachment.ContentStream, ContentEncoding.Default),
                        ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = attachment.Name //Path.GetFileName(filePath)
                    };
                    multipart.Add(attachmentMimePart);
                }

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

            return message;
        }

        //protected override MailMessage BuildMailMessage(string? from, string to, string? subject, string? body, bool isBodyHtml = true, AdditionalEmailSendingArgs? additionalEmailSendingArgs = null)
        //{
        //    //return base.BuildMailMessage(from, to, subject, body, isBodyHtml, additionalEmailSendingArgs);
        //    var message = from == null
        //        ? new MailMessage { To = { to }, Subject = subject, Body = body, IsBodyHtml = isBodyHtml }
        //        : new MailMessage(from, to, subject, body) { IsBodyHtml = isBodyHtml };

        //    if (additionalEmailSendingArgs != null)
        //    {
        //        if (additionalEmailSendingArgs.Attachments != null)
        //        {
        //            foreach (var attachment in additionalEmailSendingArgs.Attachments.Where(x => x.File != null))
        //            {
        //                var fileStream = new MemoryStream(attachment.File!);
        //                fileStream.Seek(0, SeekOrigin.Begin);

        //                // Solve the problem of garbled attachment names:
        //                // https://www.cnblogs.com/rocketRobin/p/8337055.html
        //                // https://github.com/jstedfast/MailKit/issues/264
        //                // https://github.com/jstedfast/MailKit/issues/277

        //                #region Not useful, the name becomes English and numbers

        //                // You need to register the missing character set in DomainModule's ConfigureServices Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        //                //var attachmentItem = Attachment.CreateAttachmentFromString(
        //                //    Encoding.UTF8.GetString(fileStream.ToArray()),
        //                //    attachment.Name!,
        //                //    Encoding.GetEncoding("GB18030"), //Encoding.UTF8,
        //                //    System.Net.Mime.MediaTypeNames.Image.Jpeg); 

        //                #endregion

        //                var attachmentItem = new Attachment(fileStream, attachment.Name);// , System.Net.Mime.MediaTypeNames.Application.Rtf
        //                var charset = "GB18030";
        //                attachmentItem.ContentType.CharSet = charset;
        //                //// Attachment display name
        //                //attachmentItem.ContentType.Name = attachment.Name;
        //                // Attachment download name
        //                // !! Chinese will still be garbled, to solve this problem, first use a fixed English file name, otherwise the downloaded file name suffix will be incorrect and cannot be opened, for example "璺ㄥ鐢靛晢2024骞�堟椿鍔ㄩ鍛�jpg"
        //                // I didn't expect QQ mail display name, details in the upper left corner file name, download file name are using ContentDisposition!.FileName
        //                // I have consulted the author, https://github.com/jstedfast/MailKit/issues/264#issuecomment-2178099225
        //                attachmentItem.ContentDisposition!.FileName = attachment.Name!; // "attachment" + Path.GetExtension(attachment.Name);

        //                message.Attachments.Add(attachmentItem);
        //            }
        //        }

        //        if (additionalEmailSendingArgs.CC != null)
        //        {
        //            foreach (var cc in additionalEmailSendingArgs.CC)
        //            {
        //                message.CC.Add(cc);
        //            }
        //        }
        //    }

        //    return message;
        //}
    }
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.