package com.app.wii.util;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.xml.rpc.ServiceException;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
public class SpringMailProxy {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
new SpringMailProxy().sendEmail("主題","曾军测试账号","邮箱","授权码","收件地址","127.0.0.1",2099);//127.0.0.1 本地ip,httpport 第三方代理软件的配置的端口
}
public void sendEmail(String subject,String text,String fromemail,String password,String toemail,String host,int port) throws ServiceException {
Properties properties = new Properties();
properties.setProperty("mail.debug", "true");// 是否显示调试信息(可选)
properties.setProperty("mail.smtp.auth", "true");
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setJavaMailProperties(properties);
javaMailSender.setUsername(fromemail);
javaMailSender.setPassword(password);
javaMailSender.setHost(host);
javaMailSender.setPort(port);
javaMailSender.setSession(Session.getInstance(properties));
javaMailSender.setDefaultEncoding("UTF-8");
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
// 第二个参数设置为true,表示允许添加附件
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(fromemail);
helper.setTo(toemail);
helper.setSubject(subject);
// 第二个参数为true表示需要内容为HTML格式
helper.setText(text, true);
// helper.addInline("fileId", new File("d:\\王.pngs"));
javaMailSender.send(mimeMessage);
} catch (MailException e) {
throw new ServiceException("为以下邮箱地址[" + toemail + "]发送邮件失败!"+e);
} catch (MessagingException e) {
throw new ServiceException("为以下邮箱地址[" + toemail + "]发送邮件失败!"+e);
}
}
}
作者:候鸟 出处:http://www.cnblogs.com/swite/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |