Làm thế nào để làm việc với các đính kèm trong C++

Làm thế nào để làm việc với các đính kèm trong C++

Aspose.Email FOSS for C++ provides the mapi_attachment Class để tạo attachments từ các byte thô hoặc dòng chảy, và các mapi_message Danh sách đính kèm để đọc phụ kiện từ các tập tin MSG hiện có. Bạn có thể thêm tệp đính kèm khi soạn thảo thư và kiểm tra chúng khi tải các tệp, bao gồm việc phát hiện xem bản thân một phần đính kèm có phải là một Thông điệp của người dùng.

Bước 1 - Thiết lập dự án

git clone https://github.com/aspose-email-foss/Aspose.Email-FOSS-for-Cpp.git
add_subdirectory(Aspose.Email-FOSS-for-Cpp)
target_link_libraries(your_target PRIVATE AsposeEmailFoss::AsposeEmailFoss)

Bước 2 – Thêm tệp đính kèm từ byte

Sử dụng mapi_message::add_attachment() - Thêm dữ liệu nhị phân khi tạo một thông điệp. Cung cấp tên tệp, các byte thô như a std::vector<std::uint8_t>,Và người đàn ông đó MIME Nội dung loại:

#include <filesystem>
#include <vector>
#include "aspose/email/foss/msg/mapi_message.hpp"

int main()
{
    auto message = aspose::email::foss::msg::mapi_message::create(
        "Report", "Please review the attached report.");
    message.set_sender_name("Alice");
    message.set_sender_email_address("alice@example.com");
    message.add_recipient("bob@example.com", "Bob");

    // Attach a text file
    std::vector<std::uint8_t> text_data{'H', 'e', 'l', 'l', 'o'};
    message.add_attachment("notes.txt", text_data, "text/plain");

    // Attach a binary blob
    std::vector<std::uint8_t> bin_data{0x00, 0x01, 0x02, 0x03};
    message.add_attachment("data.bin", bin_data, "application/octet-stream");

    message.save(std::filesystem::path("report.msg"));
}

Bước 3 - Thêm tệp đính kèm từ một tập tin trên Disk

Đọc tập tin vào một vector byte, sau đó chuyển nó sang add_attachment():

#include <filesystem>
#include <fstream>
#include <iterator>
#include <vector>
#include "aspose/email/foss/msg/mapi_message.hpp"

int main()
{
    // Read a file into bytes
    std::ifstream file("document.pdf", std::ios::binary);
    std::vector<std::uint8_t> pdf_bytes(
        std::istreambuf_iterator<char>(file),
        std::istreambuf_iterator<char>{});

    auto message = aspose::email::foss::msg::mapi_message::create(
        "Document", "See attached PDF.");
    message.set_sender_name("Alice");
    message.set_sender_email_address("alice@example.com");
    message.add_recipient("bob@example.com", "Bob");
    message.add_attachment("document.pdf", pdf_bytes, "application/pdf");

    message.save(std::filesystem::path("with_pdf.msg"));
}

Bước 4 – Đọc đính kèm từ một tập tin MSG hiện có

message.attachments() Trở lại a const tham chiếu đến một vector của các đối tượng gắn kết. Mỗi Exposure filename, mime_type, data (các byte thô) và content_id:

#include <fstream>
#include <iostream>
#include "aspose/email/foss/msg/mapi_message.hpp"

int main()
{
    std::ifstream input("sample.msg", std::ios::binary);
    const auto message = aspose::email::foss::msg::mapi_message::from_stream(input);

    std::cout << "Attachments: " << message.attachments().size() << '\n';
    for (std::size_t i = 0; i < message.attachments().size(); ++i)
    {
        const auto& a = message.attachments()[i];
        std::cout << "[" << (i + 1) << "]"
                  << "  name="         << a.filename
                  << "  mime="         << a.mime_type
                  << "  bytes="        << a.data.size()
                  << "  content_id="   << a.content_id
                  << '\n';
    }
}

Bước 5 – Phát hiện và truy cập vào các tin nhắn nhúng

Một số tập tin MSG chứa các tập dữ liệu khác MSG dưới dạng tệp đính kèm (đổi hướng hoặc mời họp). Sử dụng is_embedded_message() để phát hiện những điều này và truy cập thông điệp được niêm phong qua embedded_message:

#include <fstream>
#include <iostream>
#include "aspose/email/foss/msg/mapi_message.hpp"

int main()
{
    std::ifstream input("sample.msg", std::ios::binary);
    const auto message = aspose::email::foss::msg::mapi_message::from_stream(input);

    for (const auto& attachment : message.attachments())
    {
        if (attachment.is_embedded_message() && attachment.embedded_message != nullptr)
        {
            const auto& inner = *attachment.embedded_message;
            std::cout << "Embedded subject: " << inner.subject() << '\n';
            std::cout << "Embedded from:    " << inner.sender_email_address() << '\n';

            // Save the embedded message as a standalone MSG
            inner.save(std::filesystem::path("embedded.msg"));
        }
        else
        {
            std::cout << "Regular attachment: " << attachment.filename
                      << " (" << attachment.data.size() << " bytes)\n";
        }
    }
}

Bước 6 - Lưu dữ liệu đính kèm vào Disk

Trích xuất các byte đính kèm và viết chúng vào một tệp bằng cách sử dụng dòng tảng C++ tiêu chuẩn:

#include <filesystem>
#include <fstream>
#include <iostream>
#include "aspose/email/foss/msg/mapi_message.hpp"

int main()
{
    const auto message = aspose::email::foss::msg::mapi_message::from_file(
        std::filesystem::path("sample.msg"));

    const std::filesystem::path out_dir("attachments");
    std::filesystem::create_directories(out_dir);

    for (const auto& a : message.attachments())
    {
        if (!a.is_embedded_message())
        {
            const auto out_path = out_dir / a.filename;
            std::ofstream out(out_path, std::ios::binary);
            out.write(reinterpret_cast<const char*>(a.data.data()),
                      static_cast<std::streamsize>(a.data.size()));
            std::cout << "Saved: " << out_path << '\n';
        }
    }
}

Các vấn đề thường gặp và cách khắc phục

attachment.data là trống cho một gắn kết rộng rãi. Kiểm tra nguồn MSG file thực tế chứa dữ liệu đính kèm (không phải là một liên kết OLE). MSG tập tin được xuất từ một số Các máy khách thư có thể lưu trữ các tệp đính kèm dưới dạng tham chiếu bên ngoài mà thư viện không thể theo dõi.

is_embedded_message() Trở về true nhưng embedded_messagenullptr. Các header đính kèm chỉ ra MSG nhúng, nhưng dữ liệu không thể đọc được. Nguồn MSG là hợp lệ và không bị cắt.

Lưu trữ đính kèm được trích xuất không thành công với lỗi đường dẫn. Một số file attachment chứa các ký tự không hợp lệ trên hệ thống tập tin mục tiêu (ví dụ:., :, ? Có Phục vụ: Sanitise attachment.filename Trước khi xây dựng đường dẫn đầu ra.

Các tập tin MSG lớn gây ra việc sử dụng bộ nhớ cao. Đánh giámapi_message::from_file() Load Tất cả file lớn, mở container CFB dưới đây với cfb_reader để truy cập các luồng riêng lẻ mà không hoàn toàn hiện thực hóa tất cả các đính kèm.

add_attachment() Không tìm thấy trong thời gian biên soạn. Đảm bảo bạn đang sử dụng đúng bao gồm: "aspose/email/foss/msg/mapi_message.hpp".Phương pháp này là một thành viên của aspose::email::foss::msg::mapi_message.

Câu hỏi thường gặp

Những loại MIME nào tôi nên sử dụng cho các phần đính kèm?

Sử dụng tiêu chuẩn IANA MIME để định dạng tệp: "text/plain".txt, "application/pdf".pdf, "application/octet-stream" Như một Fallback cho Các file nhị phân. MIME được lưu trữ như là một attach_mime_tag Bất động sản (không tài sản).

Tôi có thể đính kèm cùng một tập tin nhiều lần không?

Mỗi cuộc gọi đến add_attachment() Add an independent attachment entry. - Tạo bản sao Tên tệp được phép; chúng được phân biệt bởi vị trí trong danh sách đính kèm.

Làm thế nào để tôi thiết lập Content-ID cho hình ảnh trong dòng?

Chuyển chuỗi ID nội dung làm đối số thứ tư để mapi_attachment::from_stream():

auto att = aspose::email::foss::msg::mapi_attachment::from_bytes(
    "logo.png", png_bytes, "image/png", "<logo-cid@example.com>");

content_id được phơi bày như attachment.content_id Khi đọc lại.

attachment.data Một bản sao hay một tham chiếu?

attachment.data a là std::vector<std::uint8_t> được lưu trữ bởi giá trị bên trong các mapi_message Truy cập vào nó không kích hoạt thêm I/O.

Tôi có thể xóa một phần đính kèm trước khi tiết kiệm không?

Các mapi_message API không phơi bày một phương pháp xóa-đính kèm trực tiếp trong phiên bản 0.1.0. Build a new message, copy the desired properties and attachments manually, và lưu đối tượng mới.

cũng thấy

 Tiếng Việt