OSDN Git Service

ver 2.23 init
[hayashilib/hayashi.git] / src / hayashi / yuu / tools / mail / SendMail.java
1 package hayashi.yuu.tools.mail;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.UnsupportedEncodingException;
7 import java.util.Properties;
8 import java.util.Vector;
9 import javax.mail.Address;
10 import javax.mail.Message;
11 import javax.mail.MessagingException;
12 import javax.mail.Session;
13 import javax.mail.Transport;
14 import javax.mail.Store;
15 import javax.mail.internet.InternetAddress;
16 import javax.mail.internet.MimeBodyPart;
17 import javax.mail.internet.MimeMessage;
18 import javax.mail.internet.MimeMultipart;
19 import javax.mail.internet.MimeUtility;
20
21 import hayashi.yuu.tools.mail.SiteData;
22
23 /**
24  * <p>Eメールを送信するためのクラス<br/>
25  * JavaMailを使用する</p>
26  * @see <a href="http://java.sun.com/products/javamail/javadocs/index.html">JavaMail API</a>
27  * 
28  * @author hayashi
29  * @version 2010/02/05  SMTPサーバーのポート番号指定を追加
30  */
31 public class SendMail
32 {
33     public static void main(java.lang.String[] args) {
34         try {
35                 SiteData siteData = new SiteData("sendmail.properties");
36                         SendMail mail = new SendMail(siteData);
37             mail.setSubject("[SendMail] SendMail テスト");
38             mail.setContent("本文\n");
39             mail.setAttachment(new File("activation-1.1.jar"));
40             mail.send();
41         }
42         catch (Exception e) {
43             e.printStackTrace();
44         }
45     }
46
47     protected Vector<String> toVector = new Vector<String>(); // プロパティ 送信先(to) の値
48     protected Vector<String> ccVector = new Vector<String>(); // プロパティ 送信先(Cc) の値
49     protected Vector<String> bccVector = new Vector<String>();    // プロパティ 送信先(Bcc) の値
50     protected String from = null;         // プロパティ 発信元(from) の値
51     protected String subject;             // プロパティ 題名(subject) の値
52     protected String content;             // プロパティ 本文(content) の値
53     protected String mailHost;            // プロパティ SMTP(mail.smtp.host) の値
54     protected String mailHostPort;        // プロパティ SMTP_PORT(mail.smtp.port) の値
55     
56     protected Vector<File> attachments = new Vector<File>();    // 添付ファイル
57     protected Vector<String> attachNames = new Vector<String>();                // 添付ファイル名
58     
59     protected boolean POP_before_SMTP = false;
60     protected boolean STARTTLS = false;
61     protected boolean USER_AUTH = false;
62     protected String popServer = "";
63     protected String userId = "";
64     protected String password ="";
65     protected Session session = null;
66     
67     /** 
68      * 新しい YuuMail インスタンスを作成する 
69      * @param mailProp  メール設定ファイルのパス名称
70      */
71     public SendMail(String mailProp) {
72         this(new SiteData(mailProp));
73     }
74
75     /**
76      * 新しい インスタンスを作成する 
77      * @param siteData メール設定値を包含したオブジェクト
78      */
79     public SendMail(SiteData siteData) {
80         super();
81         
82         if (checkItem(siteData.MAIL_SMTP)) {
83             this.setMailHost(siteData.MAIL_SMTP);
84         }
85         if (checkItem(siteData.MAIL_SMTP_PORT)) {
86             this.setMailPort(siteData.MAIL_SMTP_PORT);
87         }
88         if (checkItem(siteData.MAIL_TO)) {
89             this.toVector.add(siteData.MAIL_TO);
90         }
91         if (checkItem(siteData.MAIL_CC)) {
92             this.ccVector.add(siteData.MAIL_CC);
93         }
94         if (checkItem(siteData.MAIL_BCC)) {
95             this.bccVector.add(siteData.MAIL_BCC);
96         }
97         if (checkItem(siteData.MAIL_FROM)) {
98             this.from = siteData.MAIL_FROM;
99         }
100
101         this.POP_before_SMTP = siteData.POP_before_SMTP;
102         this.STARTTLS = siteData.STARTTLS;
103         this.USER_AUTH = siteData.USER_AUTH;
104         this.popServer = siteData.MAIL_POP;
105         this.userId = siteData.USER_ID;
106         this.password = siteData.PASSWORD;
107         
108         // メール(MimeMessageオブジェクト)を生成する
109         Properties props = System.getProperties();
110         props.put("mail.smtp.host", getMailHost());
111         props.put("mail.smtp.port", getMailPort());
112         if (this.USER_AUTH) {
113                 props.put("mail.smtp.auth", "true");
114         }
115         if (this.STARTTLS) {
116                 props.put("mail.smtp.starttls.enable", "true");
117         }
118         this.session = Session.getDefaultInstance(props, null);
119     }
120     private boolean checkItem(String itemStr) {
121         if (itemStr == null) {
122                 return false;
123         }
124         if (itemStr.trim().equals("")) {
125                 return false;
126         }
127         return true;
128     }
129     
130     /** 
131      * プロパティ mailHost の取得メソッド。
132      * @return プロパティ mailHost の値。
133      */
134     public String getMailHost() {
135         return this.mailHost;
136     }
137     
138     /** 
139      * SMTPサーバーを設定
140      *  @param mailHost SMTPサーバー名またはSMTPサーバーのIPアドレス
141     */
142     public void setMailHost(String mailHost) {
143         this.mailHost = mailHost;
144     }
145     
146     /** 
147      * プロパティ SMTPポート番号 の取得メソッド。
148      * @return SMTPポート番号を表す文字列(デシマル)
149      */
150     public String getMailPort() {
151         return this.mailHostPort;
152     }
153
154     /** 
155      * SMTPポート番号を設定
156      *  @param portStr SMTPポート番号を表す文字列(デシマル)
157      */
158     public void setMailPort(String portStr) {
159         this.mailHostPort = portStr;
160     }
161     
162     /**
163      * 送信先(To)を設定.数設定可
164      * @param to 送信先(To)
165      */
166     public void setTo(String to) {
167         if (!to.equals("")) {
168             toVector.addElement(to);
169         }
170     }
171     
172     /**
173      * 送信先(Cc)を設定。複数設定可
174      * @param cc 送信先(cc)
175      */
176     public void setCc(String cc) {
177         if (!cc.equals("")) {
178             ccVector.addElement(cc);
179         }
180     }
181     
182     /**
183      * 送信先(Bco)を設定.複数選択可
184      * @param bcc 送信先(Bcc)
185      */
186     public void setBcc(String bcc) {
187         if (!bcc.equals("")) {
188             bccVector.addElement(bcc);
189         }
190     }
191     
192     /** 
193      * プロパティ from の取得メソッド。
194      * @return プロパティ from の値。
195      */
196     public String getFrom() {
197         return from;
198     }
199     
200     /** 
201      * プロパティ 送信元(from) の設定メソッド。
202      * @param from 送信元メールアドレス
203      */
204     public void setFrom(String from) {
205         this.from = from;
206     }
207     
208     /** 
209      * プロパティ subject の取得メソッド。
210      * @return プロパティ subject の値。
211      */
212     public String getSubject() {
213         return subject;
214     }
215     
216     /**
217      * プロパティ 題名(subject) の設定メソッド。
218      * メールタイトル(題名)を設定
219      * @param subject メールタイトル(題名)
220      */
221     public void setSubject(String subject) {
222         this.subject = subject;
223     }
224     
225     /** 
226      * 本文(content)の取得メソッド。
227      * @return 本文の値。
228      */
229     public String getContent() {
230         return this.content;
231     }
232     
233     /** 
234      * 本文(content)の設定メソッド。
235      * 本文(content)を設定
236      * @param content 本文(content)
237      */
238     public void setContent(String content) {
239         this.content = content;
240     }
241     
242     /** 
243      * 添付ファイルの設定メソッド。
244      * 添付するファイル(attachment)を設定.添付ファイルは複数設定可。
245      * @param attachment 添付するファイル(attachment)
246      * @throws FileNotFoundException 添付するファイルが見つからなかった。
247      */
248     public void setAttachment(File attachment) throws FileNotFoundException {
249         new FileInputStream(attachment);    // ファイルが実存することをチェックする。
250         attachments.addElement(attachment);
251         attachNames.addElement(attachment.getName());
252     }
253     
254     /** 
255      * 添付ファイルの設定メソッド。
256      * 添付するファイル(attachment)を設定.添付ファイルは複数設定可。
257      * @param attachment 添付するファイル(attachment)
258      * @param name 添付するファイルの表示名
259      * @throws FileNotFoundException 添付するファイルが見つからなかった。
260      */
261      public void setAttachment(File attachment, String name) throws FileNotFoundException {
262          new FileInputStream(attachment);    // ファイルが実存することをチェックする。
263          attachments.addElement(attachment);
264          attachNames.addElement(name);
265      }
266      
267     /**
268      * メールを送信
269      * @throws MessagingException エラー:メールの送信に失敗しました。
270      * @throws UnsupportedEncodingException エラー:メールの文字エンコードに失敗しました。
271      */
272     public void send() throws MessagingException, UnsupportedEncodingException {
273         //-------------------------
274         // POP before SMTP 対応
275         //--
276         Store store = null;
277         if (this.POP_before_SMTP == true) {
278                 System.out.println("store.connect('"+ popServer +"', '"+ userId +"', '"+ password +"')");
279                 store = this.session.getStore("pop3");
280                 store.connect(popServer, userId, password);
281         }
282         else {
283                 System.out.println("no POP_before_SMTP!");
284         }
285
286         MimeMessage message = createMessage();
287         
288         if (this.USER_AUTH) {
289                 System.out.println("transport.connect(null, '"+ userId +"', '"+ password+"')");
290             Transport transport = this.session.getTransport("smtp");
291                 transport.connect(null, userId, password);
292                 Address[] addrs = message.getAllRecipients();
293                 for (Address addr : addrs) {
294                         System.out.println("[Addr] "+ addr.toString());
295                 }
296             transport.sendMessage(message, message.getAllRecipients());
297         }
298         else {
299                 System.out.println("no SMTP_AUTH!");
300                 Transport.send(message);
301         }
302         
303         if (this.POP_before_SMTP == true) {
304             store.close();
305         }
306     }
307     
308     /**
309      * 新規にメールインスタンスを生成する。
310      * @return  メールインスタンス
311      * @throws MessagingException メール送信に失敗しました。
312      * @throws UnsupportedEncodingException 文字エンコーディングに失敗した。
313      */
314     protected MimeMessage createMessage() throws MessagingException, UnsupportedEncodingException {
315         MimeMessage msg = new MimeMessage(this.session);
316         
317         // 送信先(To)
318         InternetAddress[] toList = new InternetAddress[toVector.size()];
319         for (int i=0; i < toVector.size(); i++) {
320             toList[i] = new InternetAddress(toVector.elementAt(i));
321         }
322         msg.setRecipients(Message.RecipientType.TO, toList);
323
324         // 送信先(Cc)
325         InternetAddress[] ccList = new InternetAddress[ccVector.size()];
326         for (int i=0; i < ccVector.size(); i++) {
327             ccList[i] = new InternetAddress(ccVector.elementAt(i));
328         }
329         msg.setRecipients(Message.RecipientType.CC, ccList);
330
331         // 送信先(Bcc)
332         InternetAddress[] bccList = new InternetAddress[bccVector.size()];
333         for (int i=0; i < bccVector.size(); i++) {
334             bccList[i] = new InternetAddress(bccVector.elementAt(i));
335         }
336         msg.setRecipients(Message.RecipientType.BCC, bccList);
337         
338         // 送信元(From)
339         msg.setFrom(new InternetAddress(getFrom()));
340
341         // 件名(Subject)
342         msg.setSubject(MimeUtility.encodeText(getSubject(), "iso-2022-jp", "B"));
343
344         // 本文(Content)
345         MimeMultipart naiyou = new MimeMultipart();
346         msg.setContent(naiyou);
347         
348         MimeBodyPart honbun = new MimeBodyPart();
349         honbun.setContent(getContent(), "text/plain; charset=\"iso-2022-jp\"");
350         naiyou.addBodyPart(honbun);
351
352         // 添付(Attachment)
353         for (int i=0; i < attachments.size(); i++) {
354             File attachFile = attachments.elementAt(i);
355             MimeBodyPart tenpu = new MimeBodyPart();
356             javax.activation.FileDataSource dfs = new javax.activation.FileDataSource(attachFile);
357             javax.activation.DataHandler dh = new javax.activation.DataHandler(dfs);
358             tenpu.setDataHandler(dh);
359             tenpu.setFileName(attachNames.elementAt(i));
360             naiyou.addBodyPart(tenpu);
361         }
362         
363         return msg;
364     }
365 }