go-gomail / gomail

The best way to send emails in Go.
MIT License
4.32k stars 572 forks source link

Chinese mail attachment name garbled #66

Open Tom-Kail opened 7 years ago

Tom-Kail commented 7 years ago

example: I sent file 会议纪要2016_11_02_11_23_08_99.txt but recipient received 浼氳绾2016_11_02_11_23_08_99.txt the LANG of centos 6.5 x86_64

LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
Tom-Kail commented 7 years ago

I guess may be missing charset=utf-8 in Content-Type lead to this problem. The message generated by gomail

Mime-Version: 1.0

Date: Thu, 10 Nov 2016 23:00:44 +0800

From: cccbackup@126.com

To: 727266990@qq.com

Subject: Hello World

Content-Type: multipart/mixed;

 boundary=3639ad93a32e1e2f2c76ce7b73c5867187dc6e8891647e752217eca83e01

--3639ad93a32e1e2f2c76ce7b73c5867187dc6e8891647e752217eca83e01

Content-Transfer-Encoding: quoted-printable

Content-Type: text/html; charset=UTF-8

Hello <b>Bob</b> and <i>Cora</i>!

--3639ad93a32e1e2f2c76ce7b73c5867187dc6e8891647e752217eca83e01

Content-Disposition: attachment; filename="暴走大事件"

Content-Transfer-Encoding: base64

Content-Type: application/octet-stream; name="暴走大事件"

5a6e6Le15Ye655yf55+l

--3639ad93a32e1e2f2c76ce7b73c5867187dc6e8891647e752217eca83e01--

and message generated by github.com/Tom-Kail/email

From: cnt <cccbackup@126.com>

To: LeoCai <727266990@qq.com>

Subject: ONLY

MIME-Version: 1.0

Content-Type: multipart/mixed;

 boundary=5fab5a3e4219c2e3a186fd32b610a146bf1b8609fff08cf38d0ddfb10a1a

--5fab5a3e4219c2e3a186fd32b610a146bf1b8609fff08cf38d0ddfb10a1a

Content-Type: text/html

Content-Transfer-Encoding:8bit

You are my owowow

--5fab5a3e4219c2e3a186fd32b610a146bf1b8609fff08cf38d0ddfb10a1a

Content-Type: application/octet-stream; charset=utf-8; name="暴走大事件"

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename="暴走大事件"

5a6e6Le15Ye655yf55+l

--5fab5a3e4219c2e3a186fd32b610a146bf1b8609fff08cf38d0ddfb10a1a--
bobcyw commented 6 years ago

Try this add a SetHeader to Attach

       //attachFileName is the attachment's file name
        baseName := filepath.Base(attachFileName)
    mediaType := mime.TypeByExtension(filepath.Ext(baseName))
    if mediaType == "" {
        mediaType = "application/octet-stream"
    }
       //m is created by gomail.NewMessage()
    m.Attach(attachFileName, gomail.SetHeader(map[string][]string{
        "Content-Type": {mediaType + `; charset=utf-8; name="` + baseName + `"`},
    }))
bobcyw commented 6 years ago

I find anotherw way to solve this problem.

baseName := mime.QEncoding.Encode("utf-8", filepath.Base(attachFileName))
m.Attach(attachFileName, gomail.Rename(baseName))