User Tools

Site Tools


Action disabled: source
blog:2025-04-23-002



2025-04-23 C# System.Net.Mail 夾帶 png 於 html mail 中

  • 在 C# 中使用 System.Net.Mail 來發送 HTML 郵件並夾帶 PNG 圖片,可以通過以下步驟實現:
    • 創建郵件物件。
    • 設置郵件的主題和內容,將內容設置為 HTML 格式。
    • 添加附件,將 PNG 圖片作為附件添加到郵件中。
    • 設置 SMTP 客戶端並發送郵件。

示例代碼

  • 下面是一個示例代碼,展示如何實現這個過程:
  • using System;
    using System.Net;
    using System.Net.Mail;
    
    class Program
    {
        static void Main()
        {
            // 設定郵件內容
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("your_email@example.com");
            mail.To.Add("recipient@example.com");
            mail.Subject = "這是一封 HTML 郵件";
            
            // 設置郵件內容為 HTML
            string htmlBody = @"
            <html>
            <body>
                <h1>你好!</h1>
                <p>這是一封包含 PNG 圖片的 HTML 郵件。</p>
                <img src='cid:myImage' alt='My Image' />
            </body>
            </html>";
            mail.Body = htmlBody;
            mail.IsBodyHtml = true;
    
            // 添加 PNG 附件
            Attachment inline = new Attachment("path_to_your_image.png");
            inline.ContentId = "myImage";
            inline.ContentDisposition.Inline = true;
            mail.Attachments.Add(inline);
    
            // 設定 SMTP 客戶端
            SmtpClient smtp = new SmtpClient("smtp.example.com");
            smtp.Port = 587; // 或者 465,根據你的 SMTP 伺服器設定
            smtp.Credentials = new NetworkCredential("your_email@example.com", "your_password");
            smtp.EnableSsl = true;
    
            // 發送郵件
            try
            {
                smtp.Send(mail);
                Console.WriteLine("郵件發送成功!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("發送郵件時出錯: " + ex.Message);
            }
            finally
            {
                // 清理
                mail.Dispose();
                smtp.Dispose();
            }
        }
    }

說明

  • MailMessage:用於創建郵件的主要類別。
  • Attachment:用於添加附件,這裡的圖片是以內嵌方式顯示的,使用 ContentId 和 src='cid:myImage' 來引用。
  • SMTP 設定:根據你的郵件伺服器配置進行相應的設置。
  • 確保替換範例中的電子郵件地址、SMTP 伺服器、端口號及圖片路徑,以符合實際需求。

TAGS

  • 5 person(s) visited this page until now.

blog/2025-04-23-002.txt · Last modified: 2025/04/23 14:17 by jethro