java发送邮件

来源:互联网 发布:中兴网络机顶盒说明书 编辑:程序博客网 时间:2024/04/28 11:33

首先导入 mail.jar


public class SendEmail {    public void sendMail(String to,String text){
        //创建连接对象,连接到邮件服务器        Properties properties = new Properties();
        //设置发送邮件的基本参数        properties.put("mail.transport.protocol","smtp");//连接协议        properties.put("mail.smtp.host","smtp.qq.com");//主机名        properties.put("mail.smtp.port","465");//端口号        properties.put("mail.smtp.auth","true");        properties.put("mail.smtp.ssl.enable","true");//设置是否使用ssl连接//        properties.put("mail.debug","true");//设置是否显示debug信息,true会在控制台显示        //得到回话对象        Session session = Session.getInstance(properties, new Authenticator() {            @Override            protected PasswordAuthentication getPasswordAuthentication() {                return new PasswordAuthentication("发件人QQ邮箱","发件人QQ邮箱密码");            }        });
        //创建邮箱对象        Message message = new MimeMessage(session);        //设置发件人        try {            message.setFrom(new InternetAddress("发件人邮箱"));            //设置收件人            message.setRecipient(RecipientType.TO,new InternetAddress(to));            //设置邮件标题            message.setSubject("注册邮件验证");            //设置时间            message.setSentDate(new Date());            //设置邮件内容            message.setContent(text,"text/html;charset=UTF-8");            //得到邮差对象            Transport transport = session.getTransport();            //连接到自己的邮箱账户            transport.connect("发件人邮箱","发件人邮箱密码(不同于普通的登录密码)");            //发送邮件            transport.sendMessage(message,message.getAllRecipients());        } catch (MessagingException e) {            e.printStackTrace();        }    }}

参考链接:http://blog.csdn.net/kenhins/article/details/17588019

  http://www.cnblogs.com/SamGroves/p/7231024.html

原创粉丝点击