java——mail邮件功能

代码都写好了报错如下:

Exception in thread "main" com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM

后来检查发现依赖的包不对,错误的包为

<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>mail</artifactId>
	<version>1.4</version>
</dependency>

改为下面就成功了

<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>mail</artifactId>
	<version>1.4.7</version>
</dependency>

代码参考

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Test {

	public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host","mail.x.com");
        props.setProperty("mail.smtp.port","587");
        Session session = Session.getInstance(props);
        session.setDebug(true);
        
        Message msg = new MimeMessage(session);
        msg.setSubject("这是一个测试程序");
        msg.setText("你好!这是一个测试程序");
        msg.setFrom(new InternetAddress("[email protected]"));
        msg.setRecipient(Message.RecipientType.TO,new InternetAddress("xx.com"));
        msg.saveChanges();

        Transport transport = session.getTransport();
        transport.connect("username","password");      
        transport.sendMessage(msg, msg.getAllRecipients());
        
        System.out.println("邮件发送成功");
        transport.close();
    }


}

转自:https://www.cnblogs.com/mr-wuxiansheng/p/6958576.html

猜你喜欢

转载自blog.csdn.net/yicai168/article/details/86588826
今日推荐