와챠의 우당탕탕 코딩 일기장

[안드로이드] 메일 보내기 본문

코딩 일기장/Android(Kotlin)

[안드로이드] 메일 보내기

minWachya 2021. 8. 13. 20:33
반응형

실행 결과

to : ~@naver.com

from : ~@gmail.com

메일 보낸 화면
보낸 메일 확인


1, 라이브러리 추가

https://code.google.com/archive/p/javamail-android/downloads

 

Google Code Archive - Long-term storage for Google Code Project Hosting.

 

code.google.com

위 링크에서 additionnal.jar, mail.jar, activation.jar 를 다운받아서 

프로젝트 안의 app > libs 폴더 안에 넣기


2, AndroidManifest.xml에 권한 설정

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


3, 비동기적으로 실행해야하기 때문에 코루틴 추가 및

libs에 넣은 라이브러리도 추가한 후 Sync

// 코루틴
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"

// 메일 보내기
implementation files('libs/activation.jar')

implementation files('libs/additionnal.jar')
implementation files('libs/mail.jar')


4, 코드 짜기

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">
<EditText
android:id="@+id/editEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="보내기"
android:textColor="@color/black"
android:backgroundTint="#aaddff"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editEmail" />
</androidx.constraintlayout.widget.ConstraintLayout>

GMailSender.kt : 메일 보내는 함수 정의

+22.05.23 수정)

비밀번호는 보안 비밀번호를 입력해야 한다!

보안 비밀번호는 여기서 확인할 수 있다. 

package com.example.emailtest
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
class GMailSender : Authenticator() {
// 보내는 사람 이메일과 비밀번호
val fromEmail = "email@gmail.com"
val password = "password_여기에_입력"
// 보내는 사람 계정 확인
override fun getPasswordAuthentication(): PasswordAuthentication {
return PasswordAuthentication(fromEmail, password)
}
// 메일 보내기
fun sendEmail(toEmail: String) {
CoroutineScope(Dispatchers.IO).launch {
val props = Properties()
props.setProperty("mail.transport.protocol", "smtp")
props.setProperty("mail.host", "smtp.gmail.com")
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.port", "465")
props.put("mail.smtp.socketFactory.port", "465")
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")
props.setProperty("mail.smtp.quitwait", "false")
// 구글에서 지원하는 smtp 정보를 받아와 MimeMessage 객체에 전달
val session = Session.getDefaultInstance(props, this@GMailSender)
// 메시지 객체 만들기
val message = MimeMessage(session)
message.sender = InternetAddress(fromEmail) // 보내는 사람 설정
message.addRecipient(Message.RecipientType.TO, InternetAddress(toEmail)) // 받는 사람 설정
message.subject = "이메일 제목" // 이메일 제목
message.setText("이메일 내용") // 이메일 내용
// 전송
Transport.send(message)
}
}
}
view raw GMailSender.kt hosted with ❤ by GitHub

MainActivity.kt : <보내기> 버튼 누르면 메일 보내도록 설정

package com.example.emailtest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val editEmail = findViewById<EditText>(R.id.editEmail)
val btnSend = findViewById<Button>(R.id.btnSend)
// <보내기> 버튼 누르면
btnSend.setOnClickListener {
val email = editEmail.text.toString()
// 이메일 보내기
GMailSender().sendEmail(email)
Toast.makeText(applicationContext, "이메일을 성공적으로 보냈습니다.", Toast.LENGTH_SHORT).show()
}
}
}
view raw MainActivity.kt hosted with ❤ by GitHub

참고

https://enfanthoon.tistory.com/112

https://stickode.com/detail.html?no=2035 

https://stackoverflow.com/questions/25610727/adding-external-library-in-android-studio

 

Adding external library in Android studio

I want to add external library https://github.com/foursquare/foursquare-android-oauth to my Android application (I use Android Studio, the instructions provided by lib author for Eclipse didn't wor...

stackoverflow.com

 

반응형
Comments