Java JavaMail配置SSL协议,使用465端口发送邮件

        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost("mail.smtp.host", "smtp.qq.com");
        sender.setPort("mail.smtp.port", "465");
        sender.setUsername(config.getUsername());
        sender.setPassword(config.getPassword());
        sender.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.timeout", "10000");
        p.setProperty("mail.smtp.auth", "true");
        // 企业邮箱必须开启协议SSL
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            logger.error("开启SSL加密异常!" + e1);
            return null;
        }
        p.setProperty("mail.smtp.ssl.enable", "true");
        p.setProperty("mail.smtp.ssl.socketFactory", sf.toString());
        sender.setJavaMailProperties(p);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于JavaMail库的简单的SMTP发送邮件程序,使用465端口进行加密传输: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SMTPClient { public static void main(String[] args) { final String username = "your_email@example.com"; final String password = "your_password"; final String recipient = "recipient_email@example.com"; final String subject = "Test Email"; final String body = "This is a test email sent using JavaMail API."; Properties props = new Properties(); props.put("mail.smtp.host", "smtp.example.com"); props.put("mail.smtp.port", "465"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.ssl.enable", "true"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); message.setSubject(subject); message.setText(body); Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { throw new RuntimeException(e); } } } ``` 其中,需要修改的部分包括: - `username`:发送邮件的邮箱账号 - `password`:发送邮件的邮箱密码 - `recipient`:接收邮件的邮箱地址 - `props.put("mail.smtp.host", "smtp.example.com")`:SMTP服务器的地址,需要根据使用的邮箱服务进行修改 其他部分可根据需要进行调整。注意,此程序需要引入JavaMail库的相关依赖。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值