zoukankan      html  css  js  c++  java
  • java的邮件系统实现

      想要java中邮件发送和接收邮件,首先需要支持SMTP- pop/pop3/IMAP协议,发送的话还需要配置文件,来对程序提供相应的接口,只需要这两个文件,就可以实现邮件的接收发送,

    协议为jar包封装好的,配置文件为下:

    MailUtils.java

    import java.util.Properties;
    
    import javax.mail.Authenticator;
    import javax.mail.Message;
    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;
    import javax.mail.internet.MimeMessage.RecipientType;
    
    public class MailUtils {
    
        public static void sendMail(String email, String emailMsg)
                throws AddressException, MessagingException {
            // 1.创建一个程序与邮件服务器会话对象 Session
    
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "SMTP");
            props.setProperty("mail.host", "smtp.126.com");//发送邮件的服务器地址 使用网易126的邮箱服务器发邮件
            props.setProperty("mail.smtp.auth", "true");// 指定验证为true
    
            // 创建验证器
            Authenticator auth = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("发送者邮箱账号", "邮箱者的密码/授权码");//授权码
                }
            };
    
            Session session = Session.getInstance(props, auth);
    
            // 2.创建一个Message,它相当于是邮件内容
            Message message = new MimeMessage(session);
    
            message.setFrom(new InternetAddress("发送者的邮箱")); // 设置发送者
    
            message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者
    
            message.setSubject("用户激活");//邮件标题
    
            message.setContent(emailMsg, "text/html;charset=utf-8");//创建格式,编码
    
            // 3.创建 Transport用于将邮件发送
    
            Transport.send(message);
        }
    }

    GitHub地址:

  • 相关阅读:
    1289大鱼吃小鱼(STL中栈的应用)
    1347旋转字符串
    2133排队接水——优先队列
    7-37 整数分解为若干项之和(20 分)
    有一个VC的bug:非标准语法
    指针的一点点用法
    好久没写的博客_数组的长度等小问题
    解决strcmp的错误以及VS的快捷键
    输入流和注释
    VS出现异常?!和十进制转二进制比是小事
  • 原文地址:https://www.cnblogs.com/YangGC/p/9027354.html
Copyright © 2011-2022 走看看