用Java发送简单的邮箱(纯文本 无附件)

用Java发送简单的邮箱(纯文本 无附件)

依赖两个工具jar mail.jar activation.jar ( jar不再更新 已经完善)

发送邮箱:SMTP协议
接收邮箱:POP3协议
SMPT服务器地址: 一般是smtp.xxx.com 比如163 是smtp.163.com qq是smtp.qq.com
流程如下(本图来自b站狂神说JAVA)
用Java发送简单的邮箱(纯文本 无附件)_第1张图片
示例代码如下:

 public static void main(String[] args) throws GeneralSecurityException, MessagingException {

        Properties prop  = new Properties();
        prop.setProperty("mail.host","smtp.qq.com");//设置QQ登陆
        prop.setProperty("mail.transport.protocol","smtp");//邮件发送协议
        prop.setProperty("mail.smtp.auth","true");//需要验证用户名密码

        //关于QQ邮箱 还要设置SSL加密  加上以下代码即可  仅QQ需要  其他邮箱不需要
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);

        //使用Java Mail发送邮件的5个步骤

        //1.创建定义整个应用程序所需的环境信息的Session对象
        //创建定义整个应用程序所需的环境变量信息的Session对象


        //QQ才有  其他邮箱不需要
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("654736673","soqdiresshiqbaji");
            }
        });

        //开启Session的debug模式 这样就可以看到程序发送Email    的运行状态
        session.setDebug(true);//默认为false  可不设置

        //2.通过session得到transport对象
        Transport ts = session.getTransport();

        //3.使用邮箱的用户名和授权码连接上邮件服务器
        ts.connect("smtp.qq.com","[email protected]","soqdiresshiqbaji");
        //soqdiresshiqbaji 为 QQ邮箱授权码

        //4.创建邮箱

        //创建邮箱对象
        MimeMessage message = new MimeMessage(session);

        //指定邮箱发件人
        message.setFrom(new InternetAddress("[email protected]"));

        //指定邮箱收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("[email protected]"));//写的自己邮箱  就是自己给自己发

        //邮件标题
        message.setSubject("用Java发送邮件");

        //邮件的 文本内容
        message.setContent("

成功啦

","text/html;charset=UTF-8"); //5.发送邮件 ts.sendMessage(message,message.getAllRecipients()); //6.关闭连接 ts.close(); }

你可能感兴趣的:(Java,java)