SendGridでメール送信を試してみた


SendGridを使用した際の備忘録として残しております。



#参考
[KotlinからSendGridを利用してメール送信する | SendGridブログ](https://sendgrid.kke.co.jp/blog/?p=8471&utm_source=google&utm_medium=cpc&utm_content=text&utm_campaign=dsa&gclid=Cj0KCQjw5PGFBhC2ARIsAIFIMNcseBGhrHIN50fJQM26coHWx39CyCjzc3t8JAJ003ZjwYLNwpkZWhEaApCYEALw_wcB)
[fuel-coroutines](https://github.com/kittinunf/fuel/tree/master/fuel-coroutines)
[Android開発でAPIキーを隠蔽してGitHubに上げる - Qiita](https://qiita.com/naoyukisugi/items/4db72f4a21d463e35019)
[特殊文字（特殊記号）の名称とHTMLへの記述の仕方 | ぱそめも](https://pc.chomemo.com/others/special_character.php)

#注意点
自分だけかもしれませんが、$argsがhtmlでなければ送信できないことを忘れてしまい、文字列として送信しようとして400番エラーになったことがありました。

#実際に試したコード

```build.gradle
dependencies {
    implementation "com.github.kittinunf.fuel:fuel:2.3.1"
    implementation "com.github.kittinunf.fuel:fuel-gson:1.9.0"
    implementation 'com.github.kittinunf.result:result:3.1.0'
    implementation 'com.github.kittinunf.fuel:fuel-coroutines:2.3.1'
    implementation 'com.github.kittinunf.fuel:fuel-android:2.2.0'
}
```

```kotlin:MainActivity.kt
package com.example.sendgridsample001

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.coroutines.awaitStringResponseResult
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.result.Result
import kotlinx.coroutines.runBlocking

class MainActivity : AppCompatActivity() {

    private var flag = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val body = StringBuilder()
        body.append("Kotlinテスト")
        main(body)
        if(flag) {
            val button = findViewById<Button>(R.id.button)
            button.setOnClickListener (object : View.OnClickListener{
                override fun onClick(v: View?) {
                    val intent = Intent(this@MainActivity, SubActivity::class.java)
                    startActivity(intent)
                }
            })

        }else{
            Log.d("[ERROR]", "送信に失敗しました。")
        }
    }
    fun main(args : StringBuilder) {
        val to = "xxxxxx@gmail.com"
        val from = "xxxxxx.x.xxxxxx@gmail.com"
        var fromName = "SenderKotlin"

        var content = """
    {
        "personalizations": [
            {
                "to": [
                    {
                        "email": "$to"
                    }
                ]
            }
        ],
        "from": {
            "email": "$from",
            "name": "$fromName"
        },
        "subject": "テスト",
        "content": [
            {
                "type": "text/plain",
                "value": "Kotlinから送った"
            },
            {
                "type": "text/html",
                "value": "<html><body>&nbsp;$args&nbsp;</body></html>"
            }
        ]
    }
    """
        runBlocking {
            FuelManager.instance.baseHeaders = mapOf("Content-Type" to "application/json", "Authorization" to "Bearer ${BuildConfig.API_KEY}")
            val (req, res, result) = "https://api.sendgrid.com/v3/mail/send".httpPost().body(content).awaitStringResponseResult()
                when(result) {
                    is Result.Failure -> {
                        val ex = result.getException()
                        println(ex)
                        flag = false
                    }
                    is Result.Success -> {
                        val data = result.get()
                        println(data)
                        when(res.statusCode) {
                            202 -> flag = true
                            400, 401, 413 -> flag = false
                            else -> flag = false
                        }
                    }
                }
                println(req)
                println(res)
                println(result)


        }
    }
}
```

```xml:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SendGrid テスト!"
        android:id="@+id/textView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:layout_width="65dp"
        android:layout_height="40dp"
        android:text="次へ"
        android:id="@+id/button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

```xml:activity_sub.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SubActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="送信完了!"
        android:id="@+id/textView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

```kotlin:SubActivity.kt
package com.example.sendgridsample001

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class SubActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sub)
    }
}
```