使用javax mail发送邮件,首先将jar包添加进来,2019年了,应该都会用maven来构建项目吧
在项目的pom文件中加入javax.mail的依赖 <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.1</version> <scope>provided</scope><!--这里你视项目情况而定--> </dependency> 开始编写java代码,如下: /** * 发送邮件 * @param subject 邮件主题 * @param content 邮件内容(支持HTML) * @param toEmailAddres 收件人 * @throws Exception * @author Monk * @date 2019年5月22日 下午6:27:27 */ private static void sendMail(String subject, String content, String toEmailAddres) throws Exception { String host = "smtp.*********.com"; //邮箱服务器地址 String port = "25"; //发送邮件的端口 String auth = "false"; //是否需要进行身份验证,视调用的邮箱而定,比方说QQ邮箱就需要,否则就会发送失败 String protocol = "smtp"; //传输协议 String mailFrom = "fajianren@email.com"; //发件人邮箱 String personalName = "fajianren"; //发件人邮箱别名 String username = "fajianren@email.com"; //发件人邮箱用户名 String password = "*******"; //发件人邮箱密码 String mailDebug = "false"; //是否开启debug String contentType = null; //邮件正文类型 Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", auth == null ? "true" : auth); props.put("mail.transport.protocol", protocol == null ? "smtp" : protocol); props.put("mail.smtp.port", port == null ? "25" : port); props.put("mail.debug", mailDebug == null ? "false" : mailDebug); Session mailSession = Session.getInstance(props); // 设置session,和邮件服务器进行通讯。 MimeMessage message = new MimeMessage(mailSession); // 设置邮件主题 message.setSubject(subject); // 设置邮件正文 message.setContent(content, contentType == null ? "text/html;charset=UTF-8" : contentType); // 设置邮件发送日期 message.setSentDate(new Date()); InternetAddress address = new InternetAddress(mailFrom, personalName); // 设置邮件发送者的地址 message.setFrom(address); // 设置邮件接收方的地址 message.setRecipients(Message.RecipientType.TO, toEmailAddres); Transport transport = null; transport = mailSession.getTransport(); message.saveChanges(); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
