javaweb发送邮箱验证

不一定成功发送,不知道啥原因

package foreiger.utils;

import java.security.Security;
import java.util.Date;
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 com.sun.net.ssl.internal.ssl.Provider;

public class MailUtils {
	private static final String username="";//邮箱用户名,即QQ账号
	private static final String password="";//邮箱授权码
	private static String text="请点击下面的链接激活您的邮箱<br><a href=http://zifurj.natappfree.cc/Foreigner/updatetx?yzm=#&email=;>"
			+ "http://zifurj.natappfree.cc/Foreigner/updatetx?yzm=#</a>";
	private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
	private static final String smtpHost="smtp.qq.com";//QQ邮箱服务器
	private static final String from = "";//自己的邮箱
	public static void sendMail(String to,String emailMsg) throws AddressException, MessagingException {
		Security.addProvider(new Provider());
        Transport transport;
        MimeMessage message;
        Properties props = new Properties();
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtp.auth", "true");
        props.put("mail.smtp.host",smtpHost);
        props.put("mail.smtp.username", username);
        props.put("mail.smtp.password", password);
        props.put("mail.debug", "true");//没什么用
        Session session = Session.getDefaultInstance(props,  new Authenticator() {
            //身份认证
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        InternetAddress[] addresses = {new InternetAddress(to)};
        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO,addresses);
        message.setSubject("歪果仁外语交流平台用户邮箱激活");
        message.setSentDate(new Date());
        String content=text.replaceAll("#", emailMsg).replaceFirst(";", to);
        message.setContent(content,"text/html;charset=utf-8");
        transport = session.getTransport("smtp");
        transport.connect(smtpHost, username, password);
        transport.send(message);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37759895/article/details/79696788