26
26

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.

[Android] Gmailアカウントでメールを送信する

Last updated at Posted at 2015-02-20
  1. Google Codeのサイトからjavamail-androidからadditionnal.jarmail.jaractivation.jarをダウンロードする。

  2. ダウンロードしたライブラリをインポートする。

  3. AndroidManifest.xmlでインターネット許可する。

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
  1. 以下のコードを実装する
メール送信コード
// UIスレッド以外で実行
try {

    final Properties property = new Properties();
    property.put("mail.smtp.host",                "smtp.gmail.com");
    property.put("mail.host",                     "smtp.gmail.com");
    property.put("mail.smtp.port",                "465");
    property.put("mail.smtp.socketFactory.port",  "465");
    property.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

    // セッション
    final Session session = Session.getInstance(property, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("[送信元アカウント]", "[パスワード]");
        }
    });

    MimeMessage mimeMsg = new MimeMessage(session);

    mimeMsg.setSubject("[メール件名]", "utf-8");
    mimeMsg.setFrom(new InternetAddress("[送信元アカウント]@gmail.com"));
    mimeMsg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress("[送信先メールアドレス]"));

    // 添付ファイル
    final MimeBodyPart txtPart = new MimeBodyPart();
    txtPart.setText("[メール本文]", "utf-8");

    final MimeBodyPart filePart = new MimeBodyPart();
    File file = new File("[添付ファイルパス]");
    FileDataSource fds = new FileDataSource(file);
    DataHandler data = new DataHandler(fds);
    filePart.setDataHandler(data);
    filePart.setFileName(MimeUtility.encodeWord("[メール本文の添付ファイル名]"));

    final Multipart mp = new MimeMultipart();
    mp.addBodyPart(txtPart);
    mp.addBodyPart(filePart);
    mimeMsg.setContent(mp);

    // メール送信する。
    final Transport transport = session.getTransport("smtp");
    transport.connect("[送信元アカウント]", "[パスワード]");
    transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
    transport.close();

} catch (MessagingException e) {

} catch (UnsupportedEncodingException e) {

} finally {

}
26
26
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
26
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?