Java代码实现简单的邮件发送

【发送激活邮件】
 邮件发送的相关的概念:
* 邮箱服务器 :如果一台电脑安装了邮箱服务器的软件,这台电脑称为是邮箱服务器.
* 电子邮箱 :其实就是邮箱服务器上的一块空间,通过电子邮箱账号访问这块空间的数据.
* 收发邮件的协议 :
* 发邮件:SMTP协议:SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。 25默认端口号
* 收邮件:POP3协议:POP3,全名为“Post Office Protocol - Version 3”,即“邮局协议版本3”。是TCP/IP协议族中的一员。默认端口是110
* 收邮件:IMAP协议:IMAP(Internet Mail Access Protocol,Internet邮件访问协议)以前称作交互邮件访问协议(Interactive Mail Access Protocol)。IMAP是斯坦福大学在1986年开发的一种邮件获取协议。
* 收发邮件的过程:

核心代码的实现:

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class MailUtils {
    public static void sendMail(String to,String code){
        try {
            //获取连接
            Properties properties =new Properties();
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override 
                protected PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication("service@store.com", "111");
                }
            });
            //构建邮件
            Message message =  new MimeMessage(session);
            message.setFrom(new InternetAddress("service@store.com"));
            //设置收件人 
            //to 收件人 、CC抄送、BCC密送、暗送
            message.setRecipient(RecipientType.TO, new InternetAddress(to));
            //主题
            message.setSubject("<h>来自中国路人甲的一封激活邮件</h>");
            //设置正文
            message.setContent("<h1>来自购物天堂黑马官方商城的激活邮件:请点击下面链接激活!</h1><h3><a href='http://localhost:8080/store_v2.0/UserServlet?method=active&code="+code+"'>http://localhost:8080/store_v2.0/UserServlet?method=active&code="+code+"</a></h3>", "text/html;charset=UTF-8");
            //发送邮件
            Transport.send(message);
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值