用spring实现的发送mail实例

借鉴别人的优点以及自己的一些加工,写出如下代码:

package test;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/**
 * 本类测试简单邮件 直接用邮件发送
 * 
 * @author Administrator
 * 
 */
public class SingleMailSend {
 public static void main(String args[]) throws MessagingException {
  JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
  // 设定邮件服务器
  //senderImpl.setHost("smtp.163.com");
  senderImpl.setHost("smtp.qq.com");
  // 建立邮件消息
 // SimpleMailMessage mailMessage = new SimpleMailMessage();
  MimeMessage mailMessage = senderImpl.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(mailMessage,true,"utf-8");
  // 设置收件人,群发邮件
  String[] array = new String[]
  {"[email protected]","[email protected]"};
  helper.setTo(array);
  //mailMessage.setTo("[email protected]");
  helper.setFrom("[email protected]");
  helper.setSubject("这是我的主题!");
  helper.setText("<p style='color:red;'>这是我的内容!</p>",true);
  //添加附件
  ClassPathResource resource = new ClassPathResource("test.jpg");
  helper.addAttachment("hello.jpg", resource);
 // 根据自己的情况,设置username
  //senderImpl.setUsername("[email protected]"); 
  senderImpl.setUsername("[email protected]"); 
  senderImpl.setPassword("你的密码"); // 根据自己的情况, 设置password
 /* Properties prop = new Properties();
  prop.put(" mail.smtp.auth ", " true "); // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
  prop.put(" mail.smtp.timeout ", " 25000 ");
  senderImpl.setJavaMailProperties(prop);*/
  // 发送邮件
  senderImpl.send(mailMessage);
  System.out.println(" 邮件发送成功.. ");
 }
}  


有问题希望大家及时提出,共同探讨!

你可能感兴趣的:(用spring实现的发送mail实例)