JavaMailを使ってgmailでメールを送る件

2014-01-07T00:00:00+00:00 Java

タイトル通り

import java.util.Properties;
import javax.mail.Authenticator;
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 Client {
    public static void main(String[] args) throws Exception {
        Properties prop = System.getProperties();
        prop.setProperty("mail.smtp.host", "smtp.gmail.com");
        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.socketFactory.port", "465");
        prop.setProperty("mail.smtp.auth", "true");

        Session ses = Session.getDefaultInstance(
            prop,
            new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("ユーザー", "パス");
                }
            }
        );

        MimeMessage mm = new MimeMessage(ses);
        mm.setFrom(new InternetAddress("メールアドレス", "ore", "iso-2022-jp"));
        mm.setRecipients(Message.RecipientType.TO, "メールアドレス");
        mm.setSubject("title", "iso-2022-jp");
        mm.setText("body text", "iso-2022-jp");

        Transport.send(mm);
    }
}

な感じでやれば良いってのはまぁググれば出てくるはずなんだが、最近なJavaMailだとJavaEEなライブラリに依存している模様

apply plugin: "java"
apply plugin: "eclipse"

repositories {
    mavenCentral()
}

dependencies {
    /* javaee-api:7.0に含まれる模様なので要らないはず
    compile "javax.mail:javax.mail-api:1.4.4"
    */
    compile "javax:javaee-api:7.0"
}

mock-javamail MahoutのLocalitySensitiveHashSearch