How to add cid to e-mail body correctly?

I’m currently working on integrating email sending with GraphMailer, alongside a rich text editor powered by Quill. My goal is to allow inline image embedding in emails directly from the editor. However, I’m facing challenges with transforming base64-encoded images into inline images (CID format) for email compatibility.

Here’s a summary of my approach:

Integration Setup:

I have successfully integrated Quill as the rich text editor, allowing users to embed images using its toolbar.
Transformation Logic:

I’ve implemented JavaScript functions to transform inline images from base64 format to CID (Content-ID) format using regex replacements.
Current Issues:

While I can attach images as files, transforming them into inline images within the email body using CID is proving tricky.
Specifically, I’m looking for guidance on properly rewriting base64 image tags into CID tags in the email body, ensuring compatibility with email clients.
Here is a simplified snippet of my JavaScript code:

// Ensure DOM content is loaded before executing JavaScript
document.addEventListener('DOMContentLoaded', async () => {
    const formMailId = 'form_mail';
    const editorContainerId = 'editor-container';
    const bodyInputId = 'body_input';

    // Validate email format using a regular expression
    const isValidEmail = (email) => {
        // Regular expression for basic email validation
        const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
        return emailRegex.test(email);
    };

    // Transform Quill editor content, specifically handling inline images
    const transformQuillContent = async (content) => {
        // Transformation logic for specific patterns like YouTube video links
        const transformations = [
            {
                pattern: /<iframes+([^>]*)src="([^"]+)"([^>]*)></iframe>/g,
                replacement: async (_, beforeSrc, src, afterSrc) => {
                    // Function to extract YouTube video ID from the URL
                    const extractYouTubeVideoId = (videoUrl) => {
                        // Implementation to extract video ID from YouTube URL
                        // ...
                    };

                    // Construct YouTube thumbnail URL based on video ID
                    const constructYouTubeThumbnailUrl = async (videoId) => {
                        // Constructing YouTube thumbnail URL logic
                        // ...
                    };

                    // Construct thumbnail URL for the video link
                    const constructThumbnailUrl = async () => {
                        // Logic to determine and construct the appropriate thumbnail URL
                        // ...
                    };

                    // Asynchronously generate and return the transformed HTML
                    const thumbnailUrl = await constructThumbnailUrl();
                    return `<a href="${videoUrl}"${[beforeSrc, afterSrc].filter(attr => attr).join(' ')} style="display: inline-block; text-decoration: none;" target="_blank" rel="noopener noreferrer"><img src="${thumbnailUrl}" alt="Video Thumbnail" style="max-width: 100%; height: auto;"></a>`;
                }
            }
            // Add more transformations as needed
        ];

        // Apply each transformation to the content using regex
        for (const transformation of transformations) {
            if (transformation.replacement instanceof Function) {
                let matches;
                while ((matches = transformation.pattern.exec(content)) !== null) {
                    const replacement = await transformation.replacement(...matches);
                    content = content.replace(matches[0], replacement);
                }
            } else {
                content = content.replace(transformation.pattern, transformation.replacement);
            }
        }

        // Return the transformed HTML content
        return content;
    };

    // Editor class for managing the Quill editor instance
    class Editor {
        constructor(editorContainerId, bodyInputId) {
            this.editorContainerId = editorContainerId;
            this.bodyInputId = bodyInputId;

            // Initialize Quill editor with specific modules and options
            this.initializeQuill();
            // Additional initialization methods like accessibility
        }

        // Method to initialize the Quill editor instance
        initializeQuill() {
            this.quill = new Quill(`#${this.editorContainerId}`, {
                theme: 'snow',
                modules: {
                    imageCompressor: {
                        quality: 0.9,
                        maxWidth: 400,
                        maxHeight: 400,
                        imageType: 'image/jpeg'
                    },
                    toolbar: ['image', 'video', 'link'] // Customize toolbar options as needed
                },
                placeholder: 'Compose email...', // Placeholder text for the editor
                formats: [
                    'header', 'font', 'size', 'bold', 'italic', 'underline', 'strike', 'blockquote',
                    'list', 'indent', 'link', 'image', 'video', 'align', 'color', 'background',
                    'script'
                ]
            });

            // Event listener for text change in the editor
            this.quill.on('text-change', () => this.handleTextChange());
        }

        // Method to handle text change in the editor
        handleTextChange() {
            // Update the hidden input field with editor's HTML content
            const html = this.quill.root.innerHTML;
            const bodyInput = document.getElementById(this.bodyInputId);
            if (bodyInput) {
                bodyInput.value = html;
            } else {
                console.error('Body input element not found.');
            }
        }

        // Method to clear editor content
        clearEditor() {
            this.quill.root.innerHTML = '';
        }
    }

    // EmailForm class to manage email form submission and validation
    class EmailForm {
        constructor(formMailId, editorContainerId, bodyInputId, quill) {
            this.form = document.getElementById(formMailId);
            this.editorContainerId = editorContainerId;
            this.bodyInputId = bodyInputId;
            this.quill = quill; // Store Quill instance for content manipulation

            // Initialize with form listener and validation setup
            if (this.form) {
                this.attachFormListener();
                // Setup real-time validation and editor validation methods
            } else {
                console.error('Form element not found.');
            }
        }

        // Method to attach form submit listener
        attachFormListener() {
            this.form.addEventListener('submit', async (event) => {
                event.preventDefault();
                if (this.validateForm()) {
                    await this.sendEmail();
                }
            });
        }

        // Method to handle form submission and send email
        async sendEmail() {
            try {
                const editorHtml = this.quill.root.innerHTML;
                const transformedBody = await transformQuillContent(editorHtml);

                // Update the hidden input field with transformed HTML content
                const bodyInput = document.getElementById(this.bodyInputId);
                if (bodyInput) {
                    bodyInput.value = transformedBody;
                } else {
                    throw new Error('Body input element not found.');
                }

                // Retrieve CC recipients and prepare form data
                const ccInput = document.getElementById('cc').value.trim();
                const ccRecipients = ccInput ? ccInput.split(',').map(email => email.trim()) : [];

                const formData = new FormData(this.form);
                formData.set('cc', JSON.stringify(ccRecipients));

                // Handle file attachments
                const attachments = document.getElementById('attachments').querySelectorAll('input[type="file"]');
                attachments.forEach(fileInput => {
                    if (fileInput.files.length > 0) {
                        formData.append('attachments[]', fileInput.files[0]);
                    }
                });

                // Submit form data to the server
                const response = await fetch(this.form.action, {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error(`Network response was not ok: ${response.statusText}`);
                }

                const data = await response.json();

                if (data.success) {
                    this.handleSuccess(data);
                } else {
                    throw new Error(data.message || 'Failed to send email.');
                }
            } catch (error) {
                console.error('Error processing content:', error);
                // Handle and log errors appropriately
            }
        }

        // Method to validate email input format
        validateEmailInput(inputElement, errorElement) {
            // Validation logic for email input
        }

        // Method to validate CC input format
        validateCCInput(inputElement, errorElement) {
            // Validation logic for CC input
        }

        // Method to validate subject input format
        validateSubjectInput(inputElement, errorElement) {
            // Validation logic for subject input
        }

        // Method to validate editor content
        validateEditorContent() {
            // Validation logic for editor content
        }

        // Method to validate the entire form
        validateForm() {
            // Comprehensive form validation logic
            return true; // Placeholder; implement actual validation
        }

        // Method to handle successful email submission
        handleSuccess(data) {
            // Handle successful email submission
        }
    }

    // Instantiate Editor and EmailForm classes
    const editor = new Editor(editorContainerId, bodyInputId);
    const emailForm = new EmailForm(formMailId, editorContainerId, bodyInputId, editor.quill);

    // Initial scan and transformation of email body content
    const initialEmailBody = editor.quill.root.innerHTML;
    const transformedInitialBody = await transformQuillContent(initialEmailBody);
    editor.quill.root.innerHTML = transformedInitialBody;

    // Add event listeners for tooltips
    const tooltipTriggers = document.querySelectorAll('.tooltip2');
    tooltipTriggers.forEach(trigger => {
        const inputField = trigger.closest('.mb-3').querySelector('input');

        trigger.addEventListener('mouseenter', () => {
            const tooltipElement = this;
            const tooltipText = inputField.getAttribute('data-tooltip2');
            if (tooltipText) {
                tooltipElement.setAttribute('data-tooltip', tooltipText);
                tooltipElement.classList.add('tooltip-visible');
            }
        });

        trigger.addEventListener('mouseleave', () => {
            const tooltipElement = this;
            tooltipElement.classList.remove('tooltip-visible');
        });
    });

    // Function to insert attachment into DOM or handle differently
    async function insertAttachment(data, cid = null) {
        // Insert attachment logic
    }

    // Function to remove attachment from DOM
    function removeAttachment(node) {
        // Remove attachment logic
    }

    // Function to scan email body and transform inline images
    async function scanEmailBody(body) {
        // Scan and transform inline images in email body
    }

    // Function to check if attachment is already inserted
    function isAttachmentInserted(data) {
        // Check if attachment is already inserted logic
    }

    // Function to select attachment file from input
    function selectAttachment() {
        // Select attachment logic
    }

    // Function to transform inline images to CID format
    async function transformInlineImages(body) {
        // Transform inline images logic
    }

    // Function to generate unique CID for attachments
    function generateUniqueCID() {
        // Generate unique CID logic
    }
});

Sorry for robust code, but to understand a logic, I think it was needed this time and really I have tried to shortern it as much as possible.

I am expecting that image which was inserted into e-mail body form will be added to attachements + will be displayed as cid image correctly upon sending, just because e-mail clients don’t accept base64 images.
currently it returns: Transformed Body:

GET cid:cid-1721043638861-ummder4x9 net::ERR_UNKNOWN_URL_SCHEME
Image (asynchronní)
transformQuillContent @ quill-editor.js:18: (line) container.innerHTML = transformedBody;
within:

const transformQuillContent = async (content) => {
        const transformedBody = await transformInlineImages(content);
        const container = document.createElement('div');
        container.innerHTML = transformedBody;
    
        const transformations = [];
    
        for (const transformation of transformations) {
            if (transformation.replacement instanceof Function) {
                let matches;
                while ((matches = transformation.pattern.exec(container.innerHTML)) !== null) {
                    const replacement = await transformation.replacement(...matches);
                    container.innerHTML = container.innerHTML.replace(matches[0], replacement);
                }
            } else {
                container.innerHTML = container.innerHTML.replace(transformation.pattern, transformation.replacement);
            }
        }
    
        return container.innerHTML;
    };

await in transformQuillContent (asynchronní)
sendEmail @ quill-editor.js:334: (line) const transformedBody = await transformQuillContent(editorHtml); within:

async sendEmail() {
try {
const editorHtml = this.quill.root.innerHTML;
const transformedBody = await transformQuillContent(editorHtml);

console.log('Transformed Body:', transformedBody);

const bodyInput = document.getElementById(this.bodyInputId);
if (bodyInput) {
bodyInput.value = transformedBody;
else {
throw new Error('Body input element not found.');
               }

const ccInput = document.getElementById('cc').value.trim();
const ccRecipients = ccInput ? ccInput.split(',').map(email => email.trim()) : [];

const formData = new FormData(this.form);
formData.set('cc', JSON.stringify(ccRecipients));

const attachments = document.getElementById('attachments').querySelectorAll('input[type="file"]');
attachments.forEach(fileInput => {
if (fileInput.files.length > 0) {
formData.append('attachments[]', fileInput.files[0]);
                    }
               });

Submit form data to server
const response = await fetch(this.form.action, {
method: 'POST',
body: formData
                });

if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
               }

const data = await response.json();

if (data.success) {
this.handleSuccess(data);
else {
throw new Error(data.message || 'Failed to send email.');
               }
catch (error) {
console.error('Error processing content:', error);
this.handleError(error);
            }
        }

(anonymní) @ quill-editor.js:285 (line): await this.sendEmail(); within:

attachFormListener() {
            this.form.addEventListener('submit', async (event) => {
                event.preventDefault();
                if (this.validateForm()) {
                    await this.sendEmail();
                }
            });
        }

Another known error is wrong handler + manipulation of attached images(standard way via button, not via quill button-inlined are duplicitly added to attachement), but this will be handled.

Actually the e-mail client is working fine and attachments are sended correctly and only issue were those inlined images, so as I expect from this community downgrades + deletion of question and since I am unable to solve it solo, then I will have to remove it and keep the old way. :/ 🙂

New contributor

PBT is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật