赞
踩
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>mailapi</artifactId>
<version>1.6.0</version>
</dependency>
邮箱发送者需要开启POP3/SMTP服务,各大公司的邮箱网上都有开启的方法,我这里使用的是SSL加密,使用的的阿里邮箱的服务器
public static void main(String[] args) { // 接收人的邮箱 String mail = "123456@qq.com"; // 发送邮件的标题 String subject = "邮箱标题"; // 发送的邮件内容 String text= "这是邮件内容"; // 邮件服务器,这里我是用的是阿里邮箱 String smtpHost = "smtp.aliyun.com"; // 服务器端口号 int smtpHost = 465; // 发件人的邮箱 String userName = "填发件人的邮箱"; // 发件人的邮箱密码 String password = "发件人的邮箱密码"; sendText(mail, subject, text, smtpHost, smtpPort, userName, password); } private static void sendText(String mail, String subject, String text, String smtpHost, int smtpPort, String userName, String password) { try { Properties properties = new Properties(); // SSL Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); properties.setProperty("mail.smtp.socketFactory.fallback", "false"); properties.put("mail.smtp.auth", "true"); properties.setProperty("mail.smtp.socketFactory.port", String.valueOf(smtpPort)); properties.setProperty("mail.smtp.host", smtpHost); properties.put("mail.smtp.port", String.valueOf(smtpPort)); Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(userName)); message.addRecipients(Message.RecipientType.TO, mail); message.setSubject(subject); message.setText(text); Transport.send(message); } catch (Exception e) { // 可根据具体业务抛出对应的异常 } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。