首先要导入基于Spring 的Jar 包!
//定义要发关Mail 的接口
public interface MailService {
/**
* 发送注册成功的邮件
* @param account
*/
void sendRegisteMail(Account account);
/**
* 发送下订单成功的邮件
* @param order
*/
void sendOrderMail(Order order);
/**
* 群发广告邮件
* @param accounts 账号列表
* @param subject 主题
* @param content 内容
*/
void sentAdMail(List<Account> accounts, String subject, String content);
}
//实现这个接口
// 要从在和本类包下的一个文件/mail_registe.txt读取文件
public class MailServiceImpl implements MailService {
private String from="liucheng_89@126.com"; //发送人邮箱地址
private String registeTemplateName = "com/liuc/service/impl/mail_registe.txt";
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
@Override
public void sendOrderMail(Order order) {
// TODO Auto-generated method stub
}
@Override
public void sendRegisteMail(Account account) {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom(this.from);
mail.setTo(account.getEmail());
mail.setSubject("恭喜你成功注册成为易买商城的会员!");
mail.setText(loadTemplateContent(registeTemplateName).replaceAll("//$//{LOGINNAME//}", account.getLoginname()));
this.mailSender.send(mail);
}
@Override
public void sentAdMail(List<Account> accounts, String subject,
String content) {
// TODO Auto-generated method stub
}
private String loadTemplateContent(String templateName){
StringBuilder sb = new StringBuilder();
BufferedReader br= null;
try{
br = new BufferedReader(
new InputStreamReader(
Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream(templateName), "UTF-8"));
String lineSeparator = System.getProperty("line.separator");
for(String str = null; (str = br.readLine()) != null;){
sb.append(str);
sb.append(lineSeparator);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
//是mail_registe.txt
亲爱的${LOGINNAME}:您好!
恭喜你成为易买商城的会员!
你的登录用户名为:${LOGINNAME}
你的登录口令为:******(隐藏)
大家好!请多多关注我!
本站网址:http://www.emall.cn
联系邮箱:hr@emall.cn
//在applicationContext-service.xml 注册
<!-- SMTP:Simple Mail Transfer Protocol)即简单邮件传输协议 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.163.com"/>
<property name="port" value="25"/>
<property name="username" value="liucheng_89"/>
<property name="password" value="xxxxxxxx"/>
<property name="defaultEncoding" value="utf-8"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="mailService" class="com.liuc.service.impl.MailServiceImpl">
<property name="mailSender" ref="mailSender"/>
</bean>