我正在尝试为Gmail设置过滤器,我需要收到已发送的电子邮件。 问题是电子邮件的“收件人”行中的电子邮件可以有许多不同的格式。我想看看是否有一种更简单的方法,然后我正在做的是统一电子邮件的格式。我只想说明我能找到并处理的每一个案例。
function getTo(email) {
// Logs the To lines of up to the first 1-500 emails in your Inbox
var threads = GmailApp.getInboxThreads(0, 75);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo();
//runs the .to emails through the data conditioning function
//emailprocess(email,emailto)
}
Logger.log(emailto);
}
}
function main () {
var email = Session.getActiveUser().getEmail();
Logger.log(email);
getTo(email)
// createToFilte(toAddress, labelName)
}
function emailprocess(email,emailto){
var emailto = emailto.toLowerCase();
switch (emailto) {
case email:
label = 0;
break;
case "john doe <johndoe@gmail.com>":
label = 0;
break;
case "<johndoe@gmail.com>":
label = 0 ;
break;
default:
label = emailto.replace('johndoe+', '');
label = label.replace("@gmail.com","")
break;
}
}
电子邮件可以采用多种不同格式,例如:
可能只是一点点。 任何帮助都会很棒。我也是最好的程序员,所以任何使这种更精简的方法都会很棒。
解决方案:
function getTo(email) {
var emailregex = /([a-zA-Z0-9_\.\+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+)/gm
var threads = GmailApp.getInboxThreads(0, 500); // Logs the To lines of up to the first 1-500 emails in your Inbox
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo()
var emailto = emailto.toLowerCase();
//Logger.log(emailto);
emailto = emailto.match(emailregex); //runs the .to emails through the data conditioning
Logger.log(emailto);
if(emailto != null){
for (var k = 0; k < emailto.length; k++) {
if (emailto[k].indexOf("+") > -1) {
var labelto = emailto[k].slice(emailto[k].indexOf("+") + 1, emailto[k].indexOf("@"));
createToFilter(emailto[k], labelto)
Logger.log(emailto[k]);
Logger.log(labelto);
}
}
}
}
}
}
答案 0 :(得分:1)
你可以试试一个电子邮件正则表达式(那里有很多),这里有一个例子:
function getTo(email) {
var emailregex = /([a-zA-Z0-9_\.\+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+)/gm
// Logs the To lines of up to the first 1-500 emails in your Inbox
var threads = GmailApp.getInboxThreads(0, 75);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo().match(emailregex);
//runs the .to emails through the data conditioning function
//emailprocess(email,emailto)
}
Logger.log(emailto);
}
}