一、 注册EmailJS账号,可通过QQ账号直接注册。
二、创建SMTP server
三、创建Templates
注意模板格式!点击保存
四、在这里获取你的Public Key
安装
npm install emailjs-com --save
实现代码
<script setup>
import { ref } from "vue";
import emailjs from "emailjs-com";
const to = ref("");
const subject = ref("");
const text = ref("");
const status = ref("");
// 替换成你的 EmailJS 配置
const serviceID = "你的Service lD:"; // 在 EmailJS 获取
const templateID = "你的Templates ID"; // 在 EmailJS 获取
const userID = "你的Public Key"; // 在 EmailJS 获取
const sendEmail = async () => {
if (!to.value || !subject.value || !text.value) {
status.value = "请填写所有字段";
return;
}
const emailParams = {
to_email: to.value,
subject: subject.value,
message: text.value
};
try {
const response = await emailjs.send(serviceID, templateID, emailParams, userID);
console.log("邮件发送成功: ", response);
status.value = "邮件发送成功!";
// 清空输入框
to.value = "";
subject.value = "";
text.value = "";
} catch (error) {
console.error("邮件发送失败: ", error);
status.value = "邮件发送失败:" + error.text;
}
};
</script>
<template>
<div class="email-form">
<h2>发送邮件</h2>
<div>
<label>收件人:</label>
<input v-model="to" type="email" placeholder="请输入收件人邮箱" />
</div>
<div>
<label>主题:</label>
<input v-model="subject" type="text" placeholder="请输入邮件主题" />
</div>
<div>
<label>内容:</label>
<textarea v-model="text" placeholder="请输入邮件内容"></textarea>
</div>
<button @click="sendEmail">发送邮件</button>
<p>{{ status }}</p>
</div>
</template>
<style scoped>
.email-form {
width: 300px;
margin: auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 10px;
box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
}
input, textarea {
width: 100%;
padding: 8px;
margin: 5px 0;
border: 1px solid #ddd;
border-radius: 5px;
}
button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>