600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Java 实现邮箱发送验证码——QQ邮箱为例

Java 实现邮箱发送验证码——QQ邮箱为例

时间:2021-10-28 20:17:56

相关推荐

Java 实现邮箱发送验证码——QQ邮箱为例

JAVA实现使用QQ邮箱发送验证码功能

QQ邮箱设置

第一步,打开QQ邮箱(地址:/);

第二步,登录后点击设置

第三步,点击账户,下拉找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务

打开Pop3/SMPT服务 ,获取邮箱授权码(需要手机验证)

第五步,开启成功后会获得一个授权码,记录下来(代码中需要使用,这个授权码并不是一定的 )

导入依赖jar包

分别是:activation.jar、commons-email-1.x.jar、mail.jar

原创作者已经整合好了,地址:/download/qq_43166448/10743081

发送邮件代码

随机生成六位验证码方法:

int verificationCode = (int) ((Math.random() * 9 + 1) * 100000);

public void sendMail(){String[] receivers = {"邮箱@", "邮箱@"};List<File> fileList = new ArrayList<>();if(receivers != null && receivers.length > 0){try{Properties properties = new Properties();//企业邮箱使用:smtp.properties.put("mail.smtp.host", "");properties.put("mail.smtp.port", "25");properties.put("mail.smtp.auth", "true");Session session = Session.getInstance(properties);MimeMessage message = new MimeMessage(session);// 发件人message.setFrom(new InternetAddress("发件人邮箱@"));// 收件人(多个)InternetAddress[] sendTo = new InternetAddress[receivers.size()]for (int i = 0; i < receivers.size(); i++) {sendTo[i] = new InternetAddress(receivers.get(i));}message.setRecipients(MimeMessage.RecipientType.TO, sendTo);// 邮件主题//message.setSubject("邮件主题")message.setSubject(title,"UTF-8")// 添加邮件的各个部分内容,包括文本内容和附件Multipart multipart = new MimeMultipart()// 添加邮件正文BodyPart contentPart = new MimeBodyPart()contentPart.setContent("邮件内容", "text/html;charset=UTF-8")multipart.addBodyPart(contentPart)// 遍历添加文件附件if (fileList != null && fileList.size() > 0) {for (File file : fileList) {BodyPart attachmentBodyPart = new MimeBodyPart()DataSource source = new FileDataSource(file)attachmentBodyPart.setDataHandler(new DataHandler(source))attachmentBodyPart.setFileName(MimeUtility.encodeText(file.getName(), "UTF-8", "B"))multipart.addBodyPart(attachmentBodyPart)}}message.setContent(multipart)message.setSentDate(new Date())message.saveChanges()Transport transport = session.getTransport()//或者为企业邮箱和密码transport.connect("发件人邮箱@", "授权码")transport.sendMessage(message, message.getAllRecipients())transport.close()}catch (Exception e) {e.printStackTrace()}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。