안드로이드에서 기본 제공하는 이메일 앱을 인텐트로 사용하지 않고,

직접 개발한 일반 앱에서 Gmail 계정을 경유하여 이메일 보내기

 

< 다운받아 설치하여야 할 라이브러리 3개>

ㅡ activation.jar   ,   additionnal.jar   ,   mail.jar

ㅡ 설치 장소 : 각 프로젝트의 "프로젝트명/libs" 폴더

ㅡ 첨부파일 3개를 PC로 다운받아서 "프로젝트명/libs" 폴더에  copy하고,

ㅡ 안드로이드 스튜디오에서 3개의 *.jar 파일에 대하여,  각각  라이브러리 import 실행

 

< 구글 계정 로그인 보안 등급 조정 >

ㅡ 송신에 사용 될 Gmail 계정의 보안등급을 하향 조정 ( 구글 홈페이지 계정보안관리 )

 

activation.jar
0.05MB
additionnal.jar
0.04MB
mail.jar
0.42MB

 

< MainActivity >

    try {
        GMailSender gMailSender = new GMailSender(myID, myPassWD);
        //GMailSender.sendMail(제목, 본문내용, 받는사람);
        gMailSender.sendMail(strTitle,     strMessage,       strPerson);
        Toast.makeText(getApplicationContext(), "송신 완료", Toast.LENGTH_SHORT).show();
        sendResultOk = true;
        button.setEnabled(false);
    } catch (SendFailedException e) {
        Toast.makeText(getApplicationContext(), "이메일 형식이 잘못되었습니다.", Toast.LENGTH_SHORT).show();
    } catch (MessagingException e) {
        Toast.makeText(getApplicationContext(), "인터넷 연결을 확인해주십시오", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
    }

 

 

< GMailSender >

package com.example.mygmailsend;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GMailSender extends javax.mail.Authenticator {
    private String mailhost = "smtp.gmail.com";
    private String user ;
    private String password ;
    private Session session;
    private String emailCode;

    public GMailSender(String user, String password) {
        this.user = user;
        this.password = password;
        emailCode = createEmailCode();
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        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 객체에 전달해준다.
        session = Session.getDefaultInstance(props, this);
    }

    public String getEmailCode() {
        return emailCode;
    } //생성된 이메일 인증코드 반환

    private String createEmailCode() { //이메일 인증코드 생성
        String[] str = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
                "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        String newCode = new String();

        for (int x = 0; x < 8; x++) {
            int random = (int) (Math.random() * str.length);
            newCode += str[random];
        }

        return newCode;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        //해당 메서드에서 사용자의 계정(id & password)을 받아 인증받으며 인증 실패시 기본값으로 반환됨.
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body, String recipients) throws Exception {
        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain")); //본문 내용을 byte단위로 쪼개어 전달
        message.setSender(new InternetAddress(user));  //본인 이메일 설정
        message.setSubject(subject); //해당 이메일의 본문 설정
        message.setDataHandler(handler);
        if (recipients.indexOf(',') > 0)
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        else
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        Transport.send(message); //메시지 전달
    }

    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }
}

 

<AndroidManifest.xml>

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

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

 

 

주) 송신에 사용될  G메일  계정의 보안등급 하향 조정 필수

Posted by LODE_RUNNER
,