nic oot log 登陆 art sport 邮件发送 dddd system
废话不多说直接上代码
1. pom 文件导入jar包
- <!--邮件发送-->
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- <version>1.4.7</version>
- </dependency>
2. 邮件方法 我用的是163 邮箱发送
- /**
- * 项目文件根路径
- * @return
- */
- public static String rootPath() {
- return System.getProperty("user.dir");
- }}
- // 发送邮件
- public static Boolean sendEmail() {
- final Properties props = new Properties();
- //登入邮箱服务器是需要验证的
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.host", "smtp.163.com");
- props.put("mail.smtp.port", 25);
- //设置协议
- props.put("mail.transport.protocol", "smtp");
- // 发件人的账号
- props.put("mail.user", "[email protected]");
- // 访问SMTP服务时需要提供的密码 非常重要 不是你登
- 陆邮箱的密码 是需要到163 邮箱设置的SMTP的密码
- props.put("mail.password", "mima");
- // 构建授权信息,用于进行SMTP进行身份验证
- Authenticator authenticator = new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- // 用户名、密码
- String userName = props.getProperty("mail.user");
- String password = props.getProperty("mail.password");
- return new PasswordAuthentication(userName, password);
- }
- };
- // 使用环境属性和授权信息,创建邮件会话
- Session mailSession = Session.getInstance(props, authenticator);
- // mailSession.setDebug(true);
- // 创建邮件消息
- MimeMessage message = new MimeMessage(mailSession);
- try {
- String nick = "";
- nick = javax.mail.internet.MimeUtility.encodeText("title");
- // 设置发件人
- InternetAddress from = new InternetAddress(nick + " <"+
- props.getProperty("mail.user") + ">");
- message.setFrom(from);
- Address[] a = new Address[1];
- // 接收方回复的邮件地址
- a[0] = new InternetAddress("[email protected]");
- message.setReplyTo(a);
- // 设置收件人
- InternetAddress to = new InternetAddress("[email protected]");
- message.setRecipient(MimeMessage.RecipientType.TO, to);
- // 设置邮件标题
- message.setSubject("mailtitle");
- //添加附件部分
- //邮件内容部分1---文本内容
- MimeBodyPart body0 = new MimeBodyPart(); //邮件中的文字部分
- body0.setContent("<p>啦啦啦啦</p>","text/html;charset=utf-8");
- //邮件内容部分2---附件1
- MimeBodyPart body1 = new MimeBodyPart(); //附件1
- body1.setDataHandler( new DataHandler( new FileDataSource
- (UlegalZCUtil.rootPath() +
- File.separator + "pdf" + File.separator + "templateOL" + ".pdf")) )
- ;//./代表项目根目录下
- body1.setFileName( MimeUtility.encodeText("拉拉.pdf")
- );//中文附件名,解决乱码
- //把上面的3部分组装在一起,设置到msg中
- MimeMultipart mm = new MimeMultipart();
- mm.addBodyPart(body0);
- mm.addBodyPart(body1);
- message.setContent(mm);
- // 设置邮件的内容体
- // message.setContent("题在我使用postman来上传图片时候
- ,死活都没过。。显示这个,问题在哪呢?",
- "text/html;charset=UTF-8");
- // 发送邮件
- Transport.send(message);
- }
- catch (Exception e) {
- String err = e.getMessage();
- // 在这里处理message内容, 格式是固定的
- System.out.println("====:"+err);
- return false;
- }
- return true;
- }
注意 密码不是邮箱的登陆密码
java springboot+maven发送邮件
来源: http://www.bubuko.com/infodetail-2355737.html