LoginSignup
2
2
この記事誰得? 私しか得しないニッチな技術で記事投稿!

2023年版 SendGrid Mail APIで送るメールの配信停止リンクを日本語化する方法

Last updated at Posted at 2023-06-15

Overview

SendGridの配信停止・購買管理リンク日本語にしたい!!

前提条件

SendGrid - 利用経験
SendGrid - DynamicTempleteを過去利用したことがある
SendGrid API - 利用経験

SendGridの登録から実装まで多くの参考サイトがありますので、そちらを参照いただけると幸いです。

実装 

SendGrid UI

Unsubscribe パネル(解説)
  • SendGrid - Dynamic Templateの画面にてUnsubscribeを選択して、ドラッグしていただけるとメール本文にUnsubscribe -Unsubscribe Preferencesが追加されます。
  • Unsubscribe -> 配信停止
  • Unsubscribe Preferences -> 購読管理(配信停止管理ができます)
    スクリーンショット 2023-06-15 23.27.33.png
日本語 Unsubscribe パネル作成
  • ADD MODULEからTEXTを選択し、メール本文に追加する

  • 追加後任意の文字列を入力する

  • リンク化したい文字列を選択すると、TEXT MODULE STYLEが表示される

  • LINKアイコンをクリックする

  • {{{unsubscribe_preferences}}}と入力後、OKを押下することで配信停止リンクを日本語で作成できる

  • 保存忘れずに :bow

  • 表記方法 公式

{{{unsubscribe}}} -> 配信停止リンク
{{{unsubscribe_preferences}}}. -> 購読管理リンク

スクリーンショット 2023-06-15 23.27.33.png

配信停止グループ作成

SendGrid API

  • 前提としてAPI KEYを作成してください - 参考
  • golangを利用した参考ソースを記載する
  • ${}には任意のものを挿入してください
  • GroupIDの設定をしない場合、DynamicTemplateでの配信停止リンクが有効化されなかった。。。私だけ?。
/*
 DynamicTemplateを利用した例
 
 - MailParamsは独自に作っているものなので、メールに付与する情報を扱う構造体だと思っていただけると幸いです。
*/
func SendEmail(params []MailParams) error {

	form := mail.NewEmail("${配信者名}", "${FROM}")
	message := mail.NewV3Mail()
	message.SetFrom(form)
	message.SetTemplateID("${TemplateID}")
	message.AddCategories("${カテゴリ}")
	message.Subject = "${件名}"

	// Unsubscribe Groupsの設定
	// - こちらを設定しないとDynamicTemplate内の配信停止などのURLは機能しない。
	asm := mail.NewASM()
	// unsubscribe Groups画面の一覧に記載があります。
	asm.SetGroupID("GroupId")
	message.SetASM(asm)

	for _, param := range params {
		p := mail.NewPersonalization()
		p.AddTos(mail.NewEmail("", param.Email))
		// メール本文の{{username}} に挿入される
		p.SetDynamicTemplateData("username", param.Username) 
		message.AddPersonalizations(p)
	}

	response, err := s.Client.Send(message)
	if err != nil {
		log.Fatalf("Error sending mail: %v", err)
		return err
	}
	log.Print("Success sending mail")
	log.Printf("Success sending mail response: %v", response.Body)
	log.Printf("Success sending mail status: %d", response.StatusCode)
	return nil
}

おまけ

テスト方法
  • Sand Boxモードを有効にする - 参考
// message.SetASM(asm)の下記に追加
settings := mail.NewMailSettings()
enabled := true
settings.SetSandboxMode(&mail.Setting{
	Enable: &enabled,
})
message.SetMailSettings(settings)
  • 用意されているドメインを利用する- 参考

@sink.sendgrid._net`を利用する.
注意点: メールが送信されることはないがメール送信カウントされる

実装で困ったら・・・APIドキュメント
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2