寫了那麼久的Java,現在才有機會寫JavaMail。之前存在一個誤解是要架設Mail Server,不過修正的是OS都有自己內建的Mail Server,也許沒有產品化的功能強大。
JavaMail目前最新版是1.4.3,在Maven放的是1.4.1,還需引入activation,作用先不深究。pom.xml設定如下:
<dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.1</version> </dependency> |
程式寫來也很簡單,片段如下:
Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); Session session = Session.getDefaultInstance(props); session.setDebug(this.debug); // boolean MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(this.from)); // 寄件者 msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(this.recipients)); msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(this.copyTos)); msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(this.blindCopyTo)); msg.setSubject(this.mailSubject); // 標題 msg.setText(this.mailContext); // 內容 msg.setSentDate(new Date()); Transport transport = session.getTransport("smtp"); transport.connect(this.host, "", ""); // this.username, this.password); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); |
大多setter屬性都是字串型態,其中收件者(Recipients)、CC和BCC若是對象有多人,和寄Mail一樣用逗號分隔mail address。
寫JavaMail確實簡單,但也遇上了編碼瓶頸待解。發到客戶的Linux端的話,把訊息內容從Big5轉ISO-8859-1是可以正常顯示中文的,簡單轉換如下:
new String(str.getBytes("Big5"), "ISO-8859-1")
可是發到AIX或是Lotus Notes的Domino Server的SMTP下,就會變亂碼…,難搞。發不出心中的Mail。