这个需求来自于Github,在script-lab的issue列表中,我看到了这个问题。
https://github.com/OfficeDev/script-lab/issues/952.
然后我做了一个例子。其实如果通过一些特殊的办法,Javascript也许也可以直接发邮件,但更加好的做法是把发送邮件的逻辑先封装起来,然后在脚本中只需要调用即可。
例如,我用Power Automate做了一个很简单的流程,可以根据输入的参数,来发送邮件。
然后需要的代码大致如下。如果你要用,你需要修改 to 这个字段的值。
$("#run").click(() => tryCatch(run));
async function run() {
await Excel.run(async (context) => {
const payload = {
to: "change to you email address",
subject: "test",
body: "body"
};
const url =
"https://prod-26.southeastasia.logic.azure.com:443/workflows/8b05f53246ee40658e6d493fa74267f6/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=kuo9GHih2PSeTsO0bHp-1o5P77sUNYVnecI9NOvgBTY";
await fetch(url, {
method: "post",
body: JSON.stringify(payload),
headers: {
"content-type": "application/json"
}
}).then((res) => console.log(res.status));
});
}
/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
try {
await callback();
} catch (error) {
// Note: In a production add-in, you'd want to notify the user through your add-in's UI.
console.error(error);
}
}
只要运行上面的代码,你指定的邮箱很快会收到邮件。
这就完全体现了新一代的脚本的威力了。我的这个系列,将每次都以一个真实的需求场景出发,给大家展示代码。如果你有一些有意思的场景,请告诉我,免费为你编写。