Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 안드로이드 앱에서 HTML 이메일 보내는 방법 완벽 가이드

이 튜토리얼에서는 Kotlin을 사용해 안드로이드 앱에서 HTML 형식의 이메일을 전송하는 방법을 단계별로 알아봅니다. 안드로이드의 Intent 시스템을 활용하면 별도의 외부 라이브러리 없이도 기기에 설치된 이메일 앱을 통해 서식이 적용된 이메일을 손쉽게 보낼 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 빈 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 'HTML 이메일 보내기' 버튼 하나를 배치하는 간단한 구성입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />

    <Button
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="sendHtmlEmail"
        android:text="Send HTML Email" />

</RelativeLayout>

3단계: 메인 액티비티 코드 작성

src/MainActivity.kt 파일에 다음 코드를 추가합니다. 핵심은 ACTION_SENDTO 인텐트와 mailto: URI를 조합하고, Html.fromHtml()을 사용해 HTML 태그가 포함된 본문을 만드는 것입니다.

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Html
import android.view.View
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
    }

    fun sendHtmlEmail(view: View?) {
        val mailId = "yourmail@gmail.com"
        val emailIntent = Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", mailId, null))
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject text here")
        emailIntent.putExtra(
            Intent.EXTRA_TEXT,
            Html.fromHtml(
                "<p><b>Some Content</b></p>" +
                "https://www.google.com" +
                "<small><p>More content</p></small>"
            )
        )
        startActivity(Intent.createChooser(emailIntent, "Send email..."))
    }
}

참고: API 24(Nougat) 이상을 지원하려면 Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY)처럼 플래그를 함께 넘겨주는 것이 좋습니다.

4단계: 매니페스트 설정

androidManifest.xml 파일에 아래 코드를 추가합니다. 특별한 권한 선언 없이 기본 액티비티 등록만으로 동작합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run ▶ 버튼을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 앱이 실행됩니다.

버튼을 누르면 이메일 앱 선택 창이 나타나고, 선택한 이메일 클라이언트에서 제목과 HTML 서식이 적용된 본문이 미리 채워진 작성 화면을 확인할 수 있습니다.