当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现简单邮件发送

Java实现简单邮件发送

2019年07月22日  | 移动技术网IT编程  | 我要评论

java mail是利用现有的邮件账户发送邮件的工具,比如说,我在网易注册一个邮箱账户,通过java mail的操控,我可以不亲自登录网易邮箱,让程序自动的使用网易邮箱发送邮件。这一机制被广泛的用在注册激活和垃圾邮件的发送等方面。
java邮件发送的大致过程是这样的:

1、构建一个继承自javax.mail.authenticator的具体类,并重写里面的getpasswordauthentication()方法。此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利。

2、构建一个properties文件,该文件中存放smtp服务器地址等参数。

3、通过构建的properties文件和javax.mail.authenticator具体类来创建一个javax.mail.session。session的创建,就相当于登录邮箱一样。剩下的自然就是新建邮件。

4、构建邮件内容,一般是javax.mail.internet.mimemessage对象,并指定发送人,收信人,主题,内容等等。

5、使用javax.mail.transport工具类发送邮件。

下面是我封装的代码,注释也比较详细。

1、首先是继承自javax.mail.authenticator的一个具体类。getpasswordauthentication()方法也就是构建一个passwordauthentication对象并返回,有点费解java mail这样的设计意图,可能是javax.mail.authenticator为我们提供了附加的保证安全的验证措施吧。

package com.mzule.simplemail;
 
import javax.mail.authenticator;
import javax.mail.passwordauthentication;
 
/**
 * 服务器邮箱登录验证
 * 
 * @author mzule
 * 
 */
public class mailauthenticator extends authenticator {
 
  /**
   * 用户名(登录邮箱)
   */
  private string username;
  /**
   * 密码
   */
  private string password;
 
  /**
   * 初始化邮箱和密码
   * 
   * @param username 邮箱
   * @param password 密码
   */
  public mailauthenticator(string username, string password) {
  this.username = username;
  this.password = password;
  }
 
  string getpassword() {
  return password;
  }
 
  @override
  protected passwordauthentication getpasswordauthentication() {
  return new passwordauthentication(username, password);
  }
 
  string getusername() {
  return username;
  }
 
  public void setpassword(string password) {
  this.password = password;
  }
 
  public void setusername(string username) {
  this.username = username;
  }
 
}

2、邮件发送类,剩下的步骤都是在这个类实现的。代码中的simplemail是封装了邮件主题和内容的一个pojo。觉得在一个方法参数中既包含主题又包含内容,不太合适,故重载了此方法。还有就是因为大多数邮箱的smtp服务器地址都是可以通过邮箱地址算出来,简单起见,提供了一个不需要smtp服务器地址的构造器。

package com.mzule.simplemail;
 
import java.util.list;
import java.util.properties;
 
import javax.mail.messagingexception;
import javax.mail.session;
import javax.mail.transport;
import javax.mail.internet.addressexception;
import javax.mail.internet.internetaddress;
import javax.mail.internet.mimemessage;
import javax.mail.internet.mimemessage.recipienttype;
 
/**
 * 简单邮件发送器,可单发,群发。
 * 
 * @author mzule
 * 
 */
public class simplemailsender {
 
  /**
   * 发送邮件的props文件
   */
  private final transient properties props = system.getproperties();
  /**
   * 邮件服务器登录验证
   */
  private transient mailauthenticator authenticator;
 
  /**
   * 邮箱session
   */
  private transient session session;
 
  /**
   * 初始化邮件发送器
   * 
   * @param smtphostname
   *        smtp邮件服务器地址
   * @param username
   *        发送邮件的用户名(地址)
   * @param password
   *        发送邮件的密码
   */
  public simplemailsender(final string smtphostname, final string username,
    final string password) {
  init(username, password, smtphostname);
  }
 
  /**
   * 初始化邮件发送器
   * 
   * @param username
   *        发送邮件的用户名(地址),并以此解析smtp服务器地址
   * @param password
   *        发送邮件的密码
   */
  public simplemailsender(final string username, final string password) {
  //通过邮箱地址解析出smtp服务器,对大多数邮箱都管用
  final string smtphostname = "smtp." + username.split("@")[1];
  init(username, password, smtphostname);
 
  }
 
  /**
   * 初始化
   * 
   * @param username
   *        发送邮件的用户名(地址)
   * @param password
   *        密码
   * @param smtphostname
   *        smtp主机地址
   */
  private void init(string username, string password, string smtphostname) {
  // 初始化props
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.host", smtphostname);
  // 验证
  authenticator = new mailauthenticator(username, password);
  // 创建session
  session = session.getinstance(props, authenticator);
  }
 
  /**
   * 发送邮件
   * 
   * @param recipient
   *        收件人邮箱地址
   * @param subject
   *        邮件主题
   * @param content
   *        邮件内容
   * @throws addressexception
   * @throws messagingexception
   */
  public void send(string recipient, string subject, object content)
    throws addressexception, messagingexception {
  // 创建mime类型邮件
  final mimemessage message = new mimemessage(session);
  // 设置发信人
  message.setfrom(new internetaddress(authenticator.getusername()));
  // 设置收件人
  message.setrecipient(recipienttype.to, new internetaddress(recipient));
  // 设置主题
  message.setsubject(subject);
  // 设置邮件内容
  message.setcontent(content.tostring(), "text/html;charset=utf-8");
  // 发送
  transport.send(message);
  }
 
  /**
   * 群发邮件
   * 
   * @param recipients
   *        收件人们
   * @param subject
   *        主题
   * @param content
   *        内容
   * @throws addressexception
   * @throws messagingexception
   */
  public void send(list<string> recipients, string subject, object content)
    throws addressexception, messagingexception {
  // 创建mime类型邮件
  final mimemessage message = new mimemessage(session);
  // 设置发信人
  message.setfrom(new internetaddress(authenticator.getusername()));
  // 设置收件人们
  final int num = recipients.size();
  internetaddress[] addresses = new internetaddress[num];
  for (int i = 0; i < num; i++) {
    addresses[i] = new internetaddress(recipients.get(i));
  }
  message.setrecipients(recipienttype.to, addresses);
  // 设置主题
  message.setsubject(subject);
  // 设置邮件内容
  message.setcontent(content.tostring(), "text/html;charset=utf-8");
  // 发送
  transport.send(message);
  }
 
  /**
   * 发送邮件
   * 
   * @param recipient
   *        收件人邮箱地址
   * @param mail
   *        邮件对象
   * @throws addressexception
   * @throws messagingexception
   */
  public void send(string recipient, simplemail mail)
    throws addressexception, messagingexception {
  send(recipient, mail.getsubject(), mail.getcontent());
  }
 
  /**
   * 群发邮件
   * 
   * @param recipients
   *        收件人们
   * @param mail
   *        邮件对象
   * @throws addressexception
   * @throws messagingexception
   */
  public void send(list<string> recipients, simplemail mail)
    throws addressexception, messagingexception {
  send(recipients, mail.getsubject(), mail.getcontent());
  }
 
}

3、调用上面的邮箱发送器,可以构建一个工厂类,工厂类可以封装创建的过程,所以通过读配置文件获取邮箱用户名,密码都会变得十分方便。下面的代码是我在写观察者模式的时候写的,只是简单演示了工厂类。

package com.mzule.dp.observer.factory;
 
import com.mzule.dp.observer.constant.mailsendertype;
import com.mzule.simplemail.simplemailsender;
 
/**
 * 发件箱工厂
 * 
 * @author mzule
 * 
 */
public class mailsenderfactory {
 
  /**
   * 服务邮箱
   */
  private static simplemailsender servicesms = null;
 
  /**
   * 获取邮箱
   * 
   * @param type 邮箱类型
   * @return 符合类型的邮箱
   */
  public static simplemailsender getsender(mailsendertype type) {
  if (type == mailsendertype.service) {
    if (servicesms == null) {
    servicesms = new simplemailsender("invisible@126.com",
      "hidden");
    }
    return servicesms;
  }
  return null;
  }
 
}

4、发送邮件,还是观察者模式demo里面的代码,呼呼。

package com.mzule.dp.observer.observer;
 
import java.util.arraylist;
import java.util.list;
import java.util.observable;
import java.util.observer;
 
import javax.mail.messagingexception;
import javax.mail.internet.addressexception;
 
import com.mzule.dp.observer.constant.mailsendertype;
import com.mzule.dp.observer.factory.mailsenderfactory;
import com.mzule.dp.observer.po.product;
import com.mzule.simplemail.simplemailsender;
 
public class productpriceobserver implements observer {
 
  @override
  public void update(observable obj, object arg) {
  product product = null;
  if (obj instanceof product) {
    product = (product) obj;
  }
  if (arg instanceof float) {
    float price = (float) arg;
    float decrease = product.getprice() - price;
    if (decrease > 0) {
    // 发送邮件
    simplemailsender sms = mailsenderfactory
      .getsender(mailsendertype.service);
    list<string> recipients = new arraylist<string>();
    recipients.add("invisible@qq.com");
    recipients.add("invisible@gmail.com");
    try {
      for (string recipient : recipients) {
      sms.send(recipient, "价格变动", "您关注的物品"
        + product.getname() + "降价了,由"
        + product.getprice() + "元降到" + price + "元,降幅达"
        + decrease + "元人民币。赶快购物吧。");
      }
    } catch (addressexception e) {
      e.printstacktrace();
    } catch (messagingexception e) {
      e.printstacktrace();
    }
    }
  }
  }
 
}

5、查看邮件是否发送成功了。
以上就是java邮件发送的全部过程,希望对大家的学习有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网