提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、Spring-Mail.xml配置
提示:记得将Spring-Mail.xml配置到环境中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.qq.com" />
<property name="port" value="587" />
<property name="username" value="xxxxxx@qq.com" />
<property name="password" value="xxxxxx" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">smtps</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
<prop key="mail.smtp.ssl.enable">true</prop>
</props>
</property>
</bean>
<bean id="mailBodyText" class="jp.co.nextep.cms.util.MailBodyBean" >
<property name="resource" value="classpath:mailBody.txt" ></property>
</bean>
</beans>
二、通过IO流,读入mailBodyText(邮件信息)
1.MailBodyBean
代码如下(示例):
package jp.co.nextep.cms.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
/**
* メールタイトル本文設定Bean
*
* @author newtouch
*
*/
public class MailBodyBean {
/** セクション名_メール送信完了_タイトル */
private final static String SECTION_SENDMAIL_TITLE = "sendMailBodyTitle";
/** セクション名_メール送信完了_本文 */
private final static String SECTION_SENDMAIL_BODY = "sendMailBodyText";
/** セクション名_パスワード変更完了_タイトル */
private final static String SECTION_CHGPASSWORD_TITLE = "chgPasswordBodyTitle";
/** セクション名_パスワード変更完了_本文 */
private final static String SECTION_CHGPASSWORD_BODY = "chgPasswordBodyText";
/** リソース */
private Resource resource;
/** メール送信完了メールBody本文 */
private Map<String, String> mailTextMap = new HashMap<String, String>();
Logger logger = Logger.getLogger(MailBodyBean.class);
/**
* リソースを取得します。
* @return リソース
*/
public Resource getResource() {
return resource;
}
/**
* リソースを設定します。
* @param resource リソース
*/
public void setResource(Resource resource) {
this.resource = resource;
readMailBodyText();
}
/**
* メール送信完了メールタイトルを取得します。
* @return メールBody本文
*/
public String getSendMailTitle(String... params) {
return mailTextMap == null ? "" : getText(mailTextMap.get(SECTION_SENDMAIL_TITLE), params);
}
/**
* メール送信完了メールBody本文を取得します。
* @return メールBody本文
*/
public String getSendMailBody(String... params) {
return mailTextMap == null ? "" : getText(mailTextMap.get(SECTION_SENDMAIL_BODY), params);
}
/**
* パスワード変更完了メールタイトルを取得します。
* @return メールBody本文
*/
public String getChgPasswordTitle(String... params) {
return mailTextMap == null ? "" : getText(mailTextMap.get(SECTION_CHGPASSWORD_TITLE), params);
}
/**
* パスワード変更完了メールBody本文を取得します。
* @return メールBody本文
*/
public String getChgPasswordBody(String... params) {
return mailTextMap == null ? "" : getText(mailTextMap.get(SECTION_CHGPASSWORD_BODY), params);
}
/**
* メール本文読込処理
*/
private void readMailBodyText() {
logger.info("メール本文読込開始...");
if (this.resource == null) {
return;
}
BufferedReader reader = null;
String line = null;
String currentSecion = null;
StringBuffer sb = null;
boolean firstFlg = false;
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(this.resource.getFile()),"utf-8");
reader = new BufferedReader(isr);
while ((line = reader.readLine()) != null) {
line = line.trim();
// ; # 開始の場合、無視
if (line.startsWith(";") || line.startsWith("#")) {
continue;
}else if (line.matches("\\[.*]")) {
if (sb != null && currentSecion != null) {
mailTextMap.put(currentSecion, sb.toString().replaceAll("[\\r\\n]+$", ""));
}
currentSecion = line.replaceFirst("\\[(.*)]", "$1");
sb = new StringBuffer();
firstFlg = true;
} else {
if (firstFlg) {
sb.append(line);
firstFlg = false;
} else {
sb.append("\r\n").append(line);
}
}
}
if (sb != null && currentSecion != null) {
mailTextMap.put(currentSecion, sb.toString().replaceAll("[\\r\\n]+$", ""));
}
} catch (FileNotFoundException e) {
logger.error("メール本文設定ファイルが存在しません。", e);
} catch (IOException e) {
logger.error("メール本文設定ファイル読込に失敗しました。", e);
} finally {
if (reader != null) {
try {
reader.close();
reader = null;
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
}
logger.info("メール本文読込終了...");
}
/**
* パラメータ入替
* @param text
* @param params
* @return
*/
public String getText(String text, String... params) {
if (params == null || params.length == 0) {
return text;
}
for (int i = 0; i < params.length; i++) {
text = text.replace("{" + i + "}", params[i]);
}
return text;
}
}
2.mailBody.text
代码如下(示例):
;メール送信完了メールタイトル
[sendMailBodyTitle]
【Database】パスワードのリセット
;メール送信完了メールBody本文
[sendMailBodyText]
パスワードをリセットしてください、下記URLにアクセスして。
下記URLにアクセスして、パスワードをリセットしてください。
{0}
※このメールは送信専用メールアドレスから自動送信しています。
ご返信いただいてもお答えできませんので、ご了承ください。
※URLの有効期限は、メールが送信されてから{1}以内です。
;パスワード変更完了メールタイトル
[chgPasswordBodyTitle]
【Database】パスワードのリセット完了
;パスワード変更完了メールBody本文
[chgPasswordBodyText]
たしまし了完パスワードのリセットが。
パスワードのリセットが完了しました。
※このメールは送信専用メールアドレスから自動送信しています。
ご返信いただいてもお答えできませんので、ご了承ください。
三、发送邮件
提示:发送了带链接和不带链接两种,但是都是以Text形式发送。
如果以Html形式发送,setText第二个参数设置为True。
/**
* トリガーファイル読み開始メール送信
*/
private void loadTextMailSend(String mailaddress) {
// To
String mailto = mailaddress;
String[] mailTo = mailto.split(",");
// Title
String mailTitle = mailBodyBean.getChgPasswordTitle();
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
messageHelper.setFrom(getProperty("sendfrom.mailAddress"));
messageHelper.setTo(mailTo);
messageHelper.setSubject(mailTitle);
messageHelper.setText(mailBodyBean.getChgPasswordBody(), false);
// 送信
mailSender.send(mimeMessage);
} catch (Exception e) {
logger.error(String.format("メール通知時にはエラーが発生しました.Details={%s}", e.toString()), e);
}
}
/**
* トリガーファイル読み開始メール送信
*/
private void loadHrefMailSend(String mailaddress, String Sid) {
// To
String mailto = mailaddress;
String[] mailTo = mailto.split(",");
// Title
String mailTitle = mailBodyBean.getSendMailTitle();
String href = this.createUrl(Sid);
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
messageHelper.setFrom(getProperty("sendfrom.mailAddress"));
messageHelper.setTo(mailTo);
messageHelper.setSubject(mailTitle);
messageHelper.setText(setMailBodyhref(href), false);
// 送信
mailSender.send(mimeMessage);
} catch (Exception e) {
logger.error(String.format("メール通知時にはエラーが発生しました.Details={%s}", e.toString()), e);
}
}
/**
* MailBody_hrefの設定
* @param href
* @return MailBody
*/
private String setMailBodyhref(String href) {
// 時間/分
String Timeout_msg = "";
String Timeout_type = getProperty("mail.url.timeout.type");
String Timeout_quantity = getProperty("mail.url.timeout.quantity");
// Timeout編集
if (Timeout_type.equals("1")) {
Timeout_msg = "時間";
}
else if(Timeout_type.equals("2")) {
Timeout_msg = "分";
}
String time = Timeout_quantity + Timeout_msg;
String body = mailBodyBean.getSendMailBody(href, time);
return body;
}
/**
* urlの設定
* @return url
*/
private String createUrl(String Sid) {
String url_temp= getProperty("server.SendMail.url");
StringBuffer url = new StringBuffer();
url.append(url_temp);
url.append(Sid);
return url.toString();
}
总结
提示:谷歌邮箱Spring-Mail配置可能有问题,需要注意。