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

  • 相关阅读:
    phpexcel导出带生成图片完美案例
    让Asp.Net WebAPI支持OData查询,排序,过滤。(转)
    Workflow笔记2——状态机工作流(转)
    WebAPI请求(转)
    WebApi参数传递总结(转)
    30分钟搞定后台登录界面(103个后台PSD源文件、素材网站)(转)
    .net 分布式架构之分布式锁实现(转)
    C#分布式事务解决方案-TransactionScope(转)
    Windows 环境下分布式跨域Session共享(转)
    Session分布式共享 = Session + Redis + Nginx(转)
  • 原文地址:https://www.cnblogs.com/YangGC/p/9027354.html
Copyright © 2011-2022 走看看