爱编程的欧巴

让我们成长吧~
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

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);
}

}
}