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地址:

  • 相关阅读:
    卸载驱动时,没有/lib/modules目录
    strcmp与strncmp的区别
    12864 显示多种图形
    环形缓冲区的应用ringbuffer
    环形缓冲区
    pthread_cond_wait 详解
    [置顶] 自己写一个简单通用的Makefile
    指针空间的申请与释放
    双向链表操作
    FreeType 管理字形
  • 原文地址:https://www.cnblogs.com/YangGC/p/9027354.html
Copyright © 2011-2022 走看看