SMTP邮件投递代码之Java调用示例

凯方全球邮SMTP邮件投递JAVA调用

//pom.xml添加javax.mail的引用,或者项目引入javax.mail的jar包
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

发信示例代码:

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class Test {
    public static void main(String[] args) {
    // 设置发件人邮箱的属性
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp-n.global-mail.cn"); // SMTP服务器地址 smtp-n.global-mail.cn 或者 smtp.global-mail.cn
        props.put("mail.smtp.port", "25"); // SMTP服务器端口

        // 启用SSL
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        
        // 创建验证信息
        Authenticator auth = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("test@example.cn", "******"); // 发送邮箱的账号和密码
            }
        };

        // 创建会话
        Session session = Session.getInstance(props, auth);

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("test@example.cn")); // 设置发件人邮箱
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@example.cn")); // 设置收件人邮箱
            message.setSubject("Testing JavaMail"); // 设置邮件主题
            message.setText("Hello, this is a test email sent using JavaMail."); // 设置邮件内容

            // 发送邮件
            Transport.send(message);
            System.out.println("Email sent successfully.");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
滚动至顶部
微信客服