You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Go通过IMAP为Gmail邮件草稿添加附件

为Go语言编写的Gmail IMAP草稿添加附件的解决方案

要给Gmail草稿添加附件,你需要构造符合MIME标准的多部分邮件——纯文本格式不支持附件。下面是修改后的完整代码,替换你原有的邮件构造逻辑即可:

package main

import (
	"bytes"
	"encoding/base64"
	"io"
	"log"
	"mime/multipart"
	"mime/quotedprintable"
	"os"
	"path/filepath"
	"time"

	"github.com/emersion/go-imap"
	"github.com/emersion/go-imap/client"
)

func main() {
	log.Println("Connecting to server...")

	// Connect to server
	c, err := client.DialTLS(os.Getenv("IMAP_SERVER"), nil)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Connected")

	// Don't forget to logout
	defer c.Logout()

	// Login
	if err := c.Login(os.Getenv("IMAP_USER"), os.Getenv("IMAP_PASSWORD")); err != nil {
		log.Fatal(err)
	}
	log.Println("Logged in")

	// 构造带附件的MIME邮件
	var b bytes.Buffer
	// 创建multipart writer,设置邮件类型为混合多部分
	writer := multipart.NewWriter(&b)
	defer writer.Close()

	// 设置邮件头部,注意Content-Type要指向multipart的边界
	b.WriteString("From: <sender@example.com>\r\n")
	b.WriteString("To: <recipient@example.com>\r\n")
	b.WriteString("Subject: 带附件的草稿测试\r\n")
	b.WriteString("Content-Type: multipart/mixed; boundary=\"" + writer.Boundary() + "\"\r\n")
	b.WriteString("\r\n")
	b.WriteString("--" + writer.Boundary() + "\r\n")

	// 添加文本内容部分
	textPart, err := writer.CreatePart(map[string][]string{
		"Content-Type":              {"text/plain; charset=utf-8"},
		"Content-Transfer-Encoding": {"quoted-printable"},
	})
	if err != nil {
		log.Fatal(err)
	}
	// 用quoted-printable编码文本内容,适配中文等非ASCII字符
	qpw := quotedprintable.NewWriter(textPart)
	qpw.Write([]byte("这是带附件的草稿测试内容"))
	qpw.Close()

	// 添加附件部分
	attachmentPath := "/path/to/your/file.pdf" // 替换为你的实际附件路径
	file, err := os.Open(attachmentPath)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	// 获取附件文件名
	filename := filepath.Base(attachmentPath)
	attachmentPart, err := writer.CreatePart(map[string][]string{
		"Content-Type":              {"application/octet-stream"},
		"Content-Transfer-Encoding": {"base64"},
		"Content-Disposition":       {"attachment; filename=\"" + filename + "\""},
	})
	if err != nil {
		log.Fatal(err)
	}
	// 用base64编码附件内容,二进制文件的标准编码方式
	b64w := base64.NewEncoder(base64.StdEncoding, attachmentPart)
	io.Copy(b64w, file)
	b64w.Close()

	// 结束multipart结构
	b.WriteString("\r\n--" + writer.Boundary() + "--\r\n")

	// Append到Gmail草稿文件夹
	if err := c.Append("[Gmail]/Drafts", nil, time.Now(), &b); err != nil {
		log.Fatal(err)
	}
	log.Println("带附件的草稿已创建")
}

关键说明:

  • MIME多部分结构:通过multipart.Writer创建multipart/mixed类型的邮件,这是同时支持文本和附件的标准格式
  • 编码处理:文本内容用quoted-printable编码(避免中文等特殊字符乱码),附件用base64编码(适配二进制文件传输)
  • 附件标识:必须通过Content-Disposition设置附件文件名,确保Gmail能正确识别为可下载的附件
  • 边界一致性:邮件头部的boundary参数要和multipart.Writer生成的边界完全一致,否则邮件结构会解析失败

注意事项:

  1. 替换代码中的发件人、收件人邮箱地址
  2. 修改attachmentPath为你的实际附件路径
  3. 确保环境变量配置正确:Gmail的IMAP服务器地址是imap.gmail.com:993,账号需开启IMAP服务,或使用应用专用密码(若开启两步验证)

内容的提问来源于stack exchange,提问作者Luiz Uatanabe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:54:24