Go服务发送XLSX附件邮件偶现异常:附件转为正文字符串
我用Go语言编写了每日生成XLSX文件的服务,依赖github.com/tealeg/xlsx库生成文件,经Base64编码后通过go-simple-mail库以邮件附件形式发送。该服务99%的情况下运行正常,但偶尔会出现邮件发送异常:附件以字符串形式出现在邮件正文中,且邮件头部带有NOOP标识。
相关代码
func (n *EmailNotifier) verifyServerConnection() error { err := n.smtpClient.Noop() if err != nil { n.smtpClient, err = n.server.Connect() if err != nil { return err } } return nil } func (n *EmailNotifier) SendFileByEmail(ctx context.Context, addresses []string, file, filename, mailSubject, body string) error { mailFile := mail.File{ Name: filename, B64Data: file, } err := n.SendEmail(ctx, addresses, mailSubject, body, &mailFile) if err != nil { return err } return nil } func (n *EmailNotifier) SendEmail(ctx context.Context, to []string, mailSubject string, body string, mailFile *mail.File) error { err := n.verifyServerConnection() if err != nil { nl.Log(ctx).WithValues().Error("Error connecting to SMTP server") return err } email := mail.NewMSG() email.SetFrom(n.server.Username).AddBcc(to...).SetSubject(mailSubject) email.SetBody(mail.TextPlain, body) if mailFile != nil { email.Attach(mailFile) if email.Error != nil { nl.Log(ctx).WithError(email.Error).WithValues("attachment error", "noop") } } err = email.Send(n.smtpClient) if err != nil { nl.Log(ctx).WithValues("subject", to).WithError(err).Error("Error sending email to") return err } return nil }
异常邮件示例
NOOP
Subject: xxxxx
Content-Type: multipart/mixed;
boundary=259435eabdfa9a8b5c048944afa23eb1b547d42281bd7269b93eeb559924
Date: Wed, 18 Jan 2023 04:00:14 +0000
Mime-Version: 1.0
From: mailto:xxx@yyy.com--259435eabdfa9a8b5c048944afa23eb1b547d42281bd7269b93eeb559924
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain; charset=UTF-8--259435eabdfa9a8b5c048944afa23eb1b547d42281bd7269b93eeb559924
Content-Disposition: attachment;
filename="xxx.xlsx"
Content-Transfer-Encoding: base64
Content-Type: application/octet-stream;
name="xxx.xlsx"UEsDBBQACAAIAAAAAAAAAAAAAAAAAAAAAAARAAAAZG9jUHJvcHMvY29yZS54bWxs0M9KxDAQx/G7
T1Fy30y6gkhpuzdPCoIKXkMydoP5M2RG23172aJVcM/zyRfy6w9Lis0nVg4lD6rVRjWYXfEhT4N6
eb7b3aqGxWZvY8k4qBOyOoxXvaPOlYqPtRBWCcjNkmLmztGgjiLUAbA7YrKsC2FeUnwrNVlhXeoE
ZN27nRD2xtxAQrHeioVzcEdbUX0nvduS9FHjGvAOMGLCLAytbuHXpiAnwosvfo5/tGBNfBGvl00u
HDY1z7Oer1e3N6aF14f7p/Wru5DPUzlUYw//Bhq/AgAA//9QSwcIO+98GtgAAABsAQAAUEsDBBQA....
已知信息
- 解码异常邮件中的Base64字符串可得到有效的XLSX文件
- 日志中未捕获到任何附件相关错误
go-simple-mail仓库无相关公开问题
猜想与求助
我猜想:使用NOOP检查SMTP连接,但收件人和附件是后续才设置的,是否可能收件人在NOOP前被设置导致异常?恳请提供其他排查思路。
内容的提问来源于stack exchange,提问作者ronihmn

