gmail-api:邮件内容格式变得扭曲(代码语言:Go)

huangapple go评论84阅读模式
英文:

gmail-api : Mail content formats are getting distorted (Code Lang : Go)

问题

我正在使用Go语言中的"google.golang.org/api/gmail/v1"来发送带有HTML内容的多封邮件。我使用for循环来发送不同内容但类型都为"html"的多封邮件。

就API而言,它工作正常,所有的邮件都能成功发送。但是只有第一封邮件以正确的格式即HTML格式发送(即邮件接收者以HTML格式接收邮件),其他用户收到的邮件都是纯文本格式(邮件正文中显示所有的HTML标签)。

是否有任何限制或条件需要处理以使其成功?

请指出我所犯的错误。

代码片段如下:

func main() {
	// 从数据库中获取数据
	recipientsList := dbRetrieval()
	fmt.Println("About to call the method")

	// 遍历所有收件人
	for indx := range recipientsList {
		time.Sleep(time.Second * 10)
		fmt.Println("The 3 second wait :", indx)
		tokenValueToBeUsed := requestRefreshToken(recipientsList[indx])
		if len(tokenValueToBeUsed) == 0 {
			err_uid := updateIsDeleted(recipientsList[indx].UserId)
			if err_uid {
				fmt.Println("Zero refresh token , so updated the DELETE")
			} else {
				fmt.Println("Zero refresh token  But couldnt update the DELETE ")
			}
		} else {
			secret, err := ioutil.ReadFile("client_secret.json")
			if err != nil {
				log.Printf("Error: %v", err)
			} else {
				conf, err := google.ConfigFromJSON(secret, gmail.GmailSendScope)
				if err != nil {
					log.Printf("Error: %v", err)
				} else {
					var tok oauth2.Token
					tok.AccessToken = tokenValueToBeUsed
					token := &tok
					client := conf.Client(oauth2.NoContext, token)
					gmailService, err := gmail.New(client)
					if err != nil {
						log.Printf("Error: %v", err)
					} else {
						var message gmail.Message

						// 对于HTML
						header := make(map[string]string)
						header["From"] = recipientsList[indx].From_Mail
						header["To"] = recipientsList[indx].To_Mail
						header["Subject"] = recipientsList[indx].Title + "\r\n\r\n" + recipientsList[indx].Body + "\r\n\r\n" + recipientsList[indx].Signature + "\r\n\r\n" + recipientsList[indx].Pixel
						header["MIME-Version"] = "1.0"
						header["Content-Type"] = "text/html; charset=\"utf-8\""
						header["Content-Transfer-Encoding"] = "base64"
						var msg string
						for k, v := range header {
							msg += fmt.Sprintf("%s: %s\r\n", k, v)
						}
						message.Raw = base64.URLEncoding.EncodeToString([]byte(msg))

						// 发送邮件
						_, err_gms := gmailService.Users.Messages.Send("me", &message).Do()
						if err_gms != nil {
							log.Printf("Error: %v", err_gms)
						} else {

							err_upd := updateStatus(recipientsList[indx].UUID)
							if err_upd {
								fmt.Println("Message sent!")
								//fmt.Println("The GMAIL response Object Details", gmailResponse)
							} else {
								fmt.Println("Message sent! But user not updated")
							}

						}
					}

				}

			}

		}

	}

}
英文:

I am using "google.golang.org/api/gmail/v1" in Go to send multiple mails with the HTML content . I am using a for loop to send multiple mails with the different content but all of the type "html".

As far as the API is considered then it's working fine and all the mails are getting delivered . But only the first mail is delivered with the right format i.e in HTML (i.e the Receiver of the mail is getting the mail in the HTML format ) and rest of the users are getting the mail with all the content as TEXT ( so all the HTML tags are visible in the body of the mail) /

Is there any limitation or condition which I need to handle to make it success ?

Kindly point out the mistake I am doing .

The code snippet is :

func main() {
// Get the data from the DB
recipientsList := dbRetrieval()
fmt.Println("About to call the method")
// Invoke the Loop for all the recipients
for indx := range recipientsList {
time.Sleep(time.Second * 10)
fmt.Println("The 3 second wait :", indx)
tokenValueToBeUsed := requestRefreshToken(recipientsList[indx])
if len(tokenValueToBeUsed) == 0 {
err_uid := updateIsDeleted(recipientsList[indx].UserId)
if err_uid {
fmt.Println("Zero refresh token , so updated the DELETE")
} else {
fmt.Println("Zero refresh token  But couldnt update the DELETE ")
}
} else {
secret, err := ioutil.ReadFile("client_secret.json")
if err != nil {
log.Printf("Error: %v", err)
} else {
conf, err := google.ConfigFromJSON(secret, gmail.GmailSendScope)
if err != nil {
log.Printf("Error: %v", err)
} else {
var tok oauth2.Token
tok.AccessToken = tokenValueToBeUsed
token := &tok
client := conf.Client(oauth2.NoContext, token)
gmailService, err := gmail.New(client)
if err != nil {
log.Printf("Error: %v", err)
} else {
var message gmail.Message
// For HTML
header := make(map[string]string)
header["From"] = recipientsList[indx].From_Mail
header["To"] = recipientsList[indx].To_Mail
header["Subject"] = recipientsList[indx].Title + "\r\n\r\n" + recipientsList[indx].Body + "\r\n\r\n" + recipientsList[indx].Signature + "\r\n\r\n" + recipientsList[indx].Pixel
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/html; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"
var msg string
for k, v := range header {
msg += fmt.Sprintf("%s: %s\r\n", k, v)
}
message.Raw = base64.URLEncoding.EncodeToString([]byte(msg))
// Send the message
_, err_gms := gmailService.Users.Messages.Send("me", &message).Do()
if err_gms != nil {
log.Printf("Error: %v", err_gms)
} else {
err_upd := updateStatus(recipientsList[indx].UUID)
if err_upd {
fmt.Println("Message sent!")
//fmt.Println("The GMAIL response Object Details", gmailResponse)
} else {
fmt.Println("Message sent! But user not updated")
}
}
}
}
}
}
}

}

答案1

得分: 0

我无法保证,但似乎您可能会遇到电子邮件字段顺序的问题,因为使用map时,顺序每次都是随机的。尝试将基于map的内容替换为类似以下的内容:

header := [][]string{
    {"To", recipientsList[indx].To_Mail},
    {"From", recipientsList[indx].From_Mail},
    {"MIME-Version", "1.0"},
    {"Content-Type", "text/html; charset=utf-8"},
    {"Content-Transfer-Encoding", "base64"},
    {"Subject", recipientsList[indx].Title + "\r\n\r\n" + recipientsList[indx].Body + "\r\n\r\n" + recipientsList[indx].Signature + "\r\n\r\n" + recipientsList[indx].Pixel},
}
var msg string
for _, v := range header {
    msg += fmt.Sprintf("%s: %s\r\n", v[0], v[1])
}

希望对您有所帮助!

英文:

I can't guarantee that but seems like you may have issues with email fields order because with map order is random every time. Try to replace map based stuff with something like:

header := [][]string{
{"To", recipientsList[indx].To_Mail},
{"From", recipientsList[indx].From_Mail},
{"MIME-Version", "1.0"},
{"Content-Type", "text/html; charset=utf-8"},
{"Content-Transfer-Encoding", "base64"},
{"Subject", recipientsList[indx].Title + "\r\n\r\n" + recipientsList[indx].Body + "\r\n\r\n" + recipientsList[indx].Signature + "\r\n\r\n" + recipientsList[indx].Pixel},
}
var msg string
for _, v := range header {
msg += fmt.Sprintf("%s: %s\r\n", v[0], v[1])
}

huangapple
  • 本文由 发表于 2017年1月20日 20:06:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/41763308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定