Java实现邮件发送

  • Post author:
  • Post category:java


发送邮件可与使用java提供的mail.jar实现。

public class EmailUtils {

    private static String fromEmail="你的邮箱";//发件邮箱
    private static String sqm="授权码";//授权码,切记只能是第三方授权码,不要用密码
    private static String host="smtp.163.com";//服务器地址

    /**
     * 参数说明:
     * 1、接收人的邮箱
     * 2、接收人姓名
     * 3、要发送的消息
     * @throws MessagingException 
     * @throws UnsupportedEncodingException 
     * @throws UnknownHostException */
    public static void sendEmail(String toEmail,String name,String msg)  {
        Properties properties=new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");//设置邮箱协议
        properties.setProperty("mail.smtp.host", host);//设置邮箱的服务器地址
        properties.setProperty("mail.smtp.auth", "true");//设置是否请求认证
        //获取会话对象---连接邮箱服务器
        Session session=Session.getInstance(properties);
        session.setDebug(true);//开启调试信息
        //创建消息对象

        try {
            MimeMessage message=new MimeMessage(session);
            //设置消息信息
            message.setFrom(new InternetAddress(fromEmail, "发件人","UTF-8"));//设置发件人信息
            message.setRecipient(MimeMessage.RecipientType.TO, 
                    new InternetAddress(toEmail, name, "utf-8"));
            message.setSubject("标题");
            message.setContent(msg,
                    "text/html;charset=utf-8");
            message.setSentDate(Calendar.getInstance().getTime());//设置发送时间
            //获取传输对象
            Transport transport=session.getTransport();
            //登录
            transport.connect(fromEmail, sqm);
            //发送邮件
    transport.sendMessage(message,message.getAllRecipients());
            //关闭
            transport.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}



版权声明:本文为u014332200原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。