uniapp 、h5、java发送邮箱

 Java代码

controller
@Log(title = "发送邮件", businessType = BusinessType.INSERT)
@RequestMapping("/sendemail")
public AjaxResult sendemail(String toMails, String mailContent) throws Exception {
        System.out.println(toMails);
        System.out.println(mailContent);


        MailUtil mailUtil = new MailUtil();
        return          mailUtil.sendMail(mailHost,fromMail,fromName,fromMailPwd,toMails,mailTitle,mailContent);
}

工具类 MailUtil       (邮件发送有文本、图片、h5样式等调自己用到的)

package com.jtport.tgt.modules.bulk;

import java.io.*;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.jtport.common.core.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestBody;

/**
* 发送邮件工具类
*/
@ComponentScan
public class MailUtil {

private final static Logger logger = LoggerFactory.getLogger(MailUtil.class);

public static String buildContent(HashMap<String,String> parameterMap) throws IOException {
String reminderDate = parameterMap.get("reminderDate");
//加载邮件html模板
File fileName = new File("Email_Template_30.html");
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));

StringBuffer buffer = new StringBuffer();
String line = "";
try {
while ((line = fileReader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
logger.error("读取文件失败,fileName:{}", fileName, e);
} finally {
fileReader.close();
}

Date date = new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String array[] = {"梅奥心磁","100",sdf.format(date),"serverId"};

//替换参数
String htmlText = MessageFormat.format(buffer.toString(), array);
return htmlText;
}

/**
* 邮件发送
* @param mailHost 邮件服务地址
* @param fromMail 发件人
* @param fromName 发件人名
* @param fromMailPwd 发件人密码
* @param toMails 收件人,多个用英文逗号分隔
* @param mailTitle 邮件标题
* @param mailContent 邮件内容
* @throws Exception
*/
public static AjaxResult sendMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
String toMails, String mailTitle, String mailContent) throws Exception {
String[] toMailArr = null;
if (toMails != null && !toMails.equals("")) {
toMailArr = toMails.split(",");
} else {
throw new Exception("邮件发送人不能为空");
}

// 邮件属性信息
Properties props = new Properties();
props.put("mail.host", mailHost);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");

Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
//session.setDebug(true); // 是否打印调试信息
toMailArr = toMails.split(",");
for (String to : toMailArr) {
MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
message.setFrom(new InternetAddress(fromMail));// 设置发件人的地址
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, fromName));// 设置收件人,并设置其接收类型为TO
message.setSubject(mailTitle);// 设置标题
message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为html
message.setSentDate(new Date());// 设置发信时间
message.saveChanges();// 存储邮件信息

// 发送邮件
Transport transport = session.getTransport();
transport.connect(fromMail, fromMailPwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
return null;
}

/**
* 邮件发送(群发)
* @param mailHost 邮件服务地址
* @param fromMail 发件人
* @param fromName 发件人名
* @param fromMailPwd 发件人密码
* @param toMails 收件人,多个用英文逗号分隔
* @param mailTitle 邮件标题
* @param mailContent 邮件内容
* @throws Exception
*/
public static void sendGroupMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
String toMails, String mailTitle, String mailContent) throws Exception {
String[] toMailArr = null;
if (toMails != null && !toMails.equals("")) {
toMailArr = toMails.split(",");
} else {
throw new Exception("邮件发送人不能为空");
}

// 邮件属性信息
Properties props = new Properties();
props.put("mail.host", mailHost);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");


Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
//session.setDebug(true); // 是否打印调试信息
MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
message.setFrom(new InternetAddress(fromMail)); // 设置发件人的地址
InternetAddress[] sendTo = new InternetAddress[toMailArr.length];
for (int i = 0; i < toMailArr.length; i++) {
sendTo[i] = new InternetAddress(toMailArr[i], fromName);
}
message.setRecipients(Message.RecipientType.TO, sendTo); // 设置收件人,并设置其接收类型为TO
message.setSubject(mailTitle); // 设置标题
message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为html
message.setSentDate(new Date()); // 设置发信时间
message.saveChanges(); // 存储邮件信息

// 发送邮件
Transport transport = session.getTransport();
transport.connect(fromMail, fromMailPwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}

/**
* 读取html文件为String
* @param htmlFileName
* @return
* @throws Exception
*/
public static String readHtmlToString(String htmlFileName) throws Exception{
InputStream is = null;
Reader reader = null;
try {
is = MailUtil.class.getClassLoader().getResourceAsStream(htmlFileName);
if (is == null) {
throw new Exception("未找到模板文件");
}
reader = new InputStreamReader(is, "UTF-8");
StringBuilder sb = new StringBuilder();
int bufferSize = 1024;
char[] buffer = new char[bufferSize];
int length = 0;
while ((length = reader.read(buffer, 0, bufferSize)) != -1){
sb.append(buffer, 0, length);
}
return sb.toString();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
logger.error("关闭io流异常", e);
}
try {
if (reader != null) {
reader.close();
}
} catch ( IOException e) {
logger.error("关闭io流异常", e);
}
}
}

}

bootstrap.yml文件配置

spring:

#邮箱基本配置
mail:
#配置smtp服务主机地址
# qq邮箱为smtp.qq.com 端口号465或587
# sina smtp.sina.cn
# aliyun smtp.aliyun.com
# 163 smtp.163.com 端口号465或994
mailHost : smtp.qq.com #发送者邮箱
fromMail : 1148586027@qq.com #发件人邮箱
mailTitle: 抖音:年仅二十开始养老 #邮箱标题
fromName: 年仅二十开始养老 #发件人
#配置密码,注意不是真正的密码,而是刚刚申请到的授权码
fromMailPwd :    #授权码
#端口号465或587
port: 465
#默认的邮件编码为UTF-8
default-encoding: UTF-8
#其他参数
properties:
mail:
#配置SSL 加密工厂
smtp:
socketFactory:
class: javax.net.ssl.SSLSocketFactory
#开启debug模式,这样邮件发送过程的日志会在控制台打印出来,方便排查错误
debug: true

#

前端代码

 

   uni.request({
                //端口号前面是本地电脑地址
                url: "http://192.168.x.xxx:6007/wtUser/sendemail",   //本地地址和后端端口地址
                data:{ //参数
                    toMails:this.email,
                    mailContent:xinxi
                },
                header: {
                    'Content-Type': 'application/json' //自定义请求头信息
                },
                sslVerify:false,
                method: 'GET', //请求方式,必须为大写
                success: (res) => {
                    console.log('接口返回------', res);
                    if (res.statusCode == 200) {
                        uni.navigateTo({
                               url: `../set/sendsucceed?email=${this.email}`
                             });
                    } else {
                        alert('!')
                    }
                },
                fail:res=>{
                    console.log(res);
                }
            })

pom文件

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

uniApp中,要实现H5页面发送语音的功能,可以借助HTML5的WebRTC(Real-Time Communication)技术,特别是getUserMedia API来获取用户的麦克风权限,并通过Blob对象将录制的音频数据转化为文件。以下是简单的步骤: 1. **请求权限**:首先,需要在`uni-app.json`文件的`permission`配置中添加`audio`权限。 ```json { "permission": { "scope.user": { "desc": "用于访问用户媒体", "permissions": ["audio"] } }, ... } ``` 2. **获取录音设备**: ```javascript uni.getUserMedia({ audio: true, success: function (stream) { // 使用stream创建录音轨道 const mediaRecorder = new MediaRecorder(stream); }, error: function (err) { console.error('Failed to get microphone: ', err); } }) ``` 3. **开始/停止录音**: ```javascript mediaRecorder.start(); // 录音完成后 mediaRecorder.stop(); ``` 4. **将音频数据转换为blob或base64**: ```javascript mediaRecorder.ondataavailable = function(e) { const blob = e.data; // 或者转为base64 const arrayBuffer = blob.arrayBuffer(); const base64String = btoa(arrayBuffer); }; ``` 5. **发送语音文件**:你可以使用ajax或者其他网络请求库(如axios),将blob或base64编码的音频数据发送到服务器。 ```javascript const formData = new FormData(); formData.append('voice', blob, 'recording.wav'); // 或formData.append('voice', base64String); uni.request({ url: '/api/uploadVoice', method: 'POST', data: formData, header: { 'Content-Type': 'multipart/form-data' }, success: function(res) { console.log('上传成功'); }, fail: function() { console.error('上传失败'); } }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值