使用sendMail发送邮件

使用sendMail发送邮件

1发送邮件必须有邮件服务器,在这里以QQ邮箱服务器为例
设置QQ邮箱支持POP,ICMP协议(百度有设置方式,在这里不再赘述)
2 下载mail.jar(注意版本,此代码示例为1.6版本)
http://download.csdn.net/download/u011238841/9926479
3 代码示例

 package com.hengc;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import com.fastjrun.util.impl.BaseUtil;

/**
 * @ClassName: EmailUtils
 * @Description: 邮件发送
 * @author kekeair
 * @date 2017年9月6日 上午9:32:02
 */
public class EmailUtils extends BaseUtil {
    public void sendEmail() {
        // 收件人电子邮箱
        String to = "zhangtingke170626@credithc.com";
        // 发件人电子邮箱
        final String from = "578221811@qq.com";
        // 设置SSL连接、邮件环境
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.auth", "true");
        // 建立邮件会话
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    // 身份认证
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from,
                                "pfgvfdrxkoxfbced");
                    }
                });
        session.setDebug(true);
        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            InternetAddress from_address = new InternetAddress(from);
            from_address.setPersonal(MimeUtility.encodeText("kevin"));
            message.setFrom(from_address);
            // Set To: 头部头字段
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));
            // Set Subject: 头部头字段
            message.setSubject("This is the Subject Line!");
            // 设置消息体
            message.setText("http://www.baidu.com");
            // 发送消息
            Transport.send(message);
        } catch (Exception mex) {
            mex.printStackTrace();
        }
    }
}

注意QQ邮箱服务器,和端口号设置也就是:
props.setProperty(“mail.smtp.host”, “smtp.qq.com”);
props.setProperty(“mail.smtp.port”, “587”);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值