java实现邮箱验证

来源:互联网 发布:一键重装软件 编辑:程序博客网 时间:2024/05/16 06:48

1.首先分析这段代码,读懂了,就会了

我是用163邮箱做的,注册一个163邮箱,然后在选择设置>>POP3/SMTP/IMAP,就到了开启POP3/SMTP服务的页面,然后把这个服务开启了就行了,需要设置一个密码,替换邮箱自己的登录密码,这样更加安全一些。下面程序中的FROM就是163邮箱,PWD就是刚设置的密码。

toEmail就是你要给谁发邮件。还有一个要提醒一下,邮箱的content(正文),subject(标题)尽量要正规,否则网易会把你发的邮件列为垃圾邮件而报554错误

public class MailUtil {public static final String HOST = "smtp.163.com";public static final String PROTOCOL = "smtp";public static final int PORT = 25;public static final String FROM = "XXX@163.com";public static final String PWD = "XXX";/** * 获取Session * @return */private static Session getSession() {Properties props = new Properties();props.put("mail.smtp.host", HOST);//设置服务器地址props.put("mail.store.protocol" , PROTOCOL);//设置协议props.put("mail.smtp.port", PORT);//设置端口props.put("mail.smtp.auth" , true);Authenticator authenticator = new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(FROM, PWD);}};Session session = Session.getDefaultInstance(props , authenticator);return session;}public static void send(String toEmail , String content) {Session session = getSession();try {            // Instantiate a message            Message msg = new MimeMessage(session);             //Set message attributes            msg.setFrom(new InternetAddress(FROM));            InternetAddress[] address = {new InternetAddress(toEmail)};            msg.setRecipients(Message.RecipientType.TO, address);            msg.setSubject("账号激活邮件");            msg.setSentDate(new Date());            msg.setContent(content , "text/html;charset=utf-8");             //Send the message            Transport.send(msg);        }        catch (MessagingException mex) {            mex.printStackTrace();        }}



0 0
原创粉丝点击