アットウィキロゴ

Java Mailでメール送信




テストコード
import java.applet.*;
import java.awt.*;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSend {

   public void send(){
        Properties property = new Properties();

       //SMTP サーバの設定
       //this.smtpHost = smtpHost;
        property.put("mail.smtp.host", "mail.ibis.ne.jp");
        property.setProperty("mail.smtp.auth", "true");
        //this.session = Session.getDefaultInstance(props, null);

        property.put("mail.smtp.host","mail.ibis.ne.jp"); // SMTPサーバ名

        property.put("mail.host","mail.ibis.ne.jp"); // 接続するホスト名

       // メールセッションを確立
       //Session session = Session.getDefaultInstance(property,null);
        Session session = Session.getInstance(property, new myAuth());
//new PasswordAuthentication("userName","ぱすわーどj") );
        //Session.getDefaultInstance()
       //Session s = Session.getDefaultInstance(property,new
PasswordAuthentication("userName","ぱすわーど"));

       // 送信メッセージを生成
       MimeMessage objMsg=new MimeMessage(session);

       try {
           // 送信先(TOのほか、CCやBCCも設定可能)
           objMsg.setRecipients(Message.RecipientType.TO, "差出人めあど");

           // Fromヘッダ
           InternetAddress objFrm = new InternetAddress("[email protected]","userName");
           objMsg.setFrom(objFrm);

           // 件名
           objMsg.setSubject("メールテスト","ISO-2022-JP");

           // 本文
           objMsg.setText("こんにちは","ISO-2022-JP");

           // メール送信
           Transport.send(objMsg);

       } catch (UnsupportedEncodingException e) {
         e.printStackTrace();

       } catch (MessagingException e) {
         e.printStackTrace();
       }
       }
     class myAuth extends Authenticator {
         protected PasswordAuthentication getPasswordAuthentication(){
             return new PasswordAuthentication("あいでぃー","ぱすわーどj");
         }
     }
}
最終更新:2012年11月15日 00:04