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 5 years have passed since last update.

SMTPSを使ってKotlinでGmailを送る

Posted at

メモ程度の内容です。
セキュリティ的に問題があるので、Gmail API を使うことが推奨されています。
しかし、私自身上手くできなかったのでとりあえずこちらでやってみたという感じです。
出来たらいいですね…頑張ります。

build.gradle.kts
// ...
dependencies {
// ...
    implementation("com.sun.mail:javax.mail:1.6.2")
}
import javax.mail.Message
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage

/*
 * https://myaccount.google.com/lesssecureapps
 * 安全性の低いアプリの許可を "有効" にしなければいけない
 */

fun main(){
    // System.setProperty("GMAIL_USER", "ユーザー名)
    // System.setProperty("GMAIL_PASSWORD", "パスワード")
    GmailUser(System.getProperty("GMAIL_USER"), System.getProperty("GMAIL_PASSWORD")).send("宛先@example.com", "タイトル", "本文")
}

class GmailUser(private val user: String, private val password: String) {
    fun send(to: String, title: String, text: String) {
        val properties = System.getProperties()
        properties["mail.smtp.host"] = "smtp.gmail.com"
        properties["mail.smtp.socketFactory.port"] = "465"
        properties["mail.smtp.socketFactory.class"] = "javax.net.ssl.SSLSocketFactory"
        properties["mail.smtp.auth"] = "true"
        properties["mail.smtp.port"] = "465"

        try {
            val session = Session.getDefaultInstance(properties)

            val message = MimeMessage(session).apply {
                setFrom(InternetAddress("$user@gmail.com"))
                setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))
                subject = title
                setText(text)
            }

            Transport.send(message, user, password)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
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?