0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2021-06-06

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

参考

KotlinからSendGridを利用してメール送信する | SendGridブログ
fuel-coroutines
Android開発でAPIキーを隠蔽してGitHubに上げる - Qiita
特殊文字(特殊記号)の名称とHTMLへの記述の仕方 | ぱそめも

注意点

自分だけかもしれませんが、$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'
}
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)


        }
    }
}
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>
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>
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)
    }
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?