从阿里云发送邮件

我本地部署好项目并测试完成以后发送到服务器,并再测试玩,结果不行

弄得我百思不得其解,最后我问度娘

度娘告诉我是因为邮件发送是走25端口的,这时候我才恍然大悟,去安全组里把25号端口的出入口打开,再发布到服务器上测试,依然不行

然后我在问度娘

度娘告诉我因为国内所有的服务器提供商都把25号端口给屏蔽了,因为防止垃圾邮件泛滥

只有2种方法,第一种向阿里云解封,第二种方法用465号端口

解封是不可能解封的,解封了也不能通过smtp发邮件,所以也没得用

所以只能通过465端口了

import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class sslMailUtil {
    private static final String email = "";
    private static final String password = "";
    private static final String smtpName = "";

    public static boolean sendMail(String toEmail, String content, String title) {
        Properties prop = new Properties();
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.host", smtpName);
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        Session s = Session.getDefaultInstance(prop, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                PasswordAuthentication pa = new PasswordAuthentication(email, password);
                return pa;
            }
        });
        s.setDebug(true);
        MimeMessage mimeMessage = new MimeMessage(s);
        try {
            mimeMessage.setFrom(new InternetAddress(email));
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
            mimeMessage.setSubject(title);
            mimeMessage.setSentDate(new Date());
            mimeMessage.setText(content);
            mimeMessage.setContent(content, "text/html;charset=UTF-8");
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    public static void main(String[] args) {
        sslMailUtil.sendMail("", "你来啦", "感谢使用!");

    }
}

说明

成员变量分别是发送方的邮件,发送邮件的授权码,对应smpt服务器(改成对应的126就是smtp.126.com)

main方法可以用来测试参数分别是接收方的邮箱,邮件正文,邮件标题

还有千万别忘了 mimeMessage.setContent(content, "text/html;charset=UTF-8");这样可以发送标签和超链接