发送邮件

看了些别人写的代码,他们会把邮件的各个属性用javaBean(getXXX()/setXXX())包装起来,然后各种调用。

不同业务有不用需求,反正殊途同归,精简事例如下(自己发给自己):

1. 下载javax.mail.jar

2. 代码如下:

public class MailTuesday {
  // 邮件内容
  private final static String FROM = "it@xxx.com";
  private final static String TO = "it@xxx.com";
  private final static String CC = "it@xxx.com";
  private final static String SUBJECT = "test";       
  private final static String CONTENT = "test";    
  // SMTP邮件服务器   
  private final static String HOST = "xxx.xxx.xxx.xx";          
  // SMTP邮件服务器默认端口 
  private final static String PORT = "26";      
  //邮箱用户信息
  private final static String USERNAME = "it@xxx.com";
  private final static String PASSWORD = "12345#";
  //
  public static void main(String[] args){
  // 用于连接邮件服务器的参数配置
  Properties props = new Properties();
  props.put("mail.smtp.host", HOST);  
  props.put("mail.smtp.port", PORT);  
  // 根据参数配置,创建会话对象
  Session session= Session.getDefaultInstance(props);
  // 创建邮件对象
  MimeMessage message = new MimeMessage(session);
  try {
    // 完善邮件对象(添加邮件参数)
    message.setFrom(FROM);
    message.setRecipients(MimeMessage.RecipientType.TO, TO);
    message.setRecipients(MimeMessage.RecipientType.CC, CC);
    message.setSubject(SUBJECT, "UTF-8");
    message.setContent(CONTENT, "text/html;charset=UTF-8");
    message.setSentDate(new Date());
    message.saveChanges();
    // 链接邮件服务器,并发送邮件,完成后关闭链接
    Transport transport = session.getTransport("smtp");
    transport.connect(HOST, USERNAME, PASSWORD);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
   } catch (MessagingException e) {
    e.printStackTrace();
   }
  }
}
posted @ 2017-03-10 14:48  ☀Beans✡✌  阅读(112)  评论(0编辑  收藏  举报