feat: unify SMTP and optional IMAP account settings

This commit is contained in:
abaishu0730 committed 2026-10-27 10:53:46 +08:00
1 parent 39afafefa7
commit 7104b6745c
8 files changed
+56 -14

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
'use strict';
const providers={'163.com':['smtp.163.com','imap.163.com'],'126.com':['smtp.126.com','imap.126.com'],'qq.com':['smtp.qq.com','imap.qq.com'],'foxmail.com':['smtp.qq.com','imap.qq.com'],'yeah.net':['smtp.yeah.net','imap.yeah.net']};
function expandAccount(input,old,address){
const preset=providers[address.split('@')[1]];const shared=Object.hasOwn(input,'password');
const result={...input,senders:input.senders??old?.senders??[],enabled:input.enabled??old?.enabled??false};
for(const [index,kind] of ['smtp','imap'].entries()){
const previous=old?.[kind],given=input[kind]||{};
result[kind]={host:previous?.host||preset?.[index]||'',port:previous?.port||(kind==='smtp'?465:993),security:previous?.security||'tls',user:previous?.user||address,...given};
result[kind].password=given.password!==undefined&&given.password!==''?given.password:shared?input.password:(given.password??'');
}
return result;
}
module.exports={expandAccount};
+4 -4
View File
@@ -22,12 +22,12 @@ class MailService{
});}
async withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
history(id,input){return this.exclusive(id,async()=>{
const config=this.store.channelSecret(id);
const config=this.store.channelSecret(id);if(config.receiveEnabled===false)fail('此邮箱未启用 IMAP 收信。',409);
try{const result=await this.withImap(config.imap,client=>require('./history.cjs').readHistory(client,input));this.store.guard(id,config.version);return result;}
catch(error){if([400,404,409,413].includes(error.status))throw error;fail(safeError(error,'IMAP'));}
});}
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱仅支持查询已发送邮件。',409);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能收取模板。',409);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱仅支持查询已发送邮件。',409);let smtp=false,imap=false,message=c.receiveEnabled===false?'SMTP 连接正常(IMAP 未启用)':'SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}if(c.receiveEnabled!==false)try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能收取模板。',409);if(c.receiveEnabled===false)fail('此邮箱未启用 IMAP 收信。',409);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});try{const epoch=String(client.mailbox.uidValidity),cursor=this.store.cursor(id);const sameEpoch=cursor.epoch===epoch;const last=sameEpoch?(cursor.uid||0):0;const query={since:new Date(sameEpoch&&cursor.since?cursor.since:Date.now()-7*86400000),...(last?{uid:(last+1)+':*'}:{})};const found=await client.search(query,{uid:true});const uids=(found||[]).filter(uid=>uid>last).sort((a,b)=>a-b).slice(0,50);
for(const uid of uids){if(this.stopped)break;this.store.guard(id,c.version);const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
if(!/^\[模板\]/.test((info.envelope?.subject||'').trim())){this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,uid);});continue;}
@@ -42,7 +42,7 @@ class MailService{
this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected};
}catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});}
sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST','类别名称':'测试通知','订单明细':'订单号:TEST 机芯号:CORE 产品型号:MODEL 客户简称:示例 出货方式:CBU 总数量:1','存放地址':'示例归档目录(测试数据)'};const rendered=require('./content.cjs').appendSignature(renderTemplate(t,values),{...c.signature,channelId:c.id,version:c.version});const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.receiveEnabled!==false&&c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);}
}
module.exports={MailService};
+9 -5
View File
@@ -32,19 +32,23 @@ class MailStore{
encode(id,value){try{return this.vault.encode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
decode(id,value){try{return this.vault.decode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
row(id){const row=this.db.prepare('SELECT * FROM channels WHERE id=?').get(id);if(!row)fail('邮箱不存在。',404);return row;}
channelSecret(id){const row=this.row(id);return {...this.decode(id,row.payload),id,version:row.version};}
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp?.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
channelSecret(id){const row=this.row(id);return {receiveEnabled:true,...this.decode(id,row.payload),id,version:row.version};}
publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp?.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap?.password},state};}
channels(){return this.db.prepare('SELECT id FROM channels ORDER BY rowid').all().map(r=>this.publicChannel(r.id));}
saveChannel(input){return this.transaction(()=>{
if(!input||typeof input!=='object')fail('邮箱配置无效。');const old=input.id?this.channelSecret(input.id):null;if(old&&old.version!==input.version)fail('邮箱已被修改,请刷新后重试。',409);
const id=old?.id||crypto.randomUUID(),address=email(input.email);const existing=this.db.prepare('SELECT id FROM channels WHERE email=?').get(address);if(existing&&existing.id!==id)fail('此邮箱已托管,请使用已有邮箱。',409);
if(input.enabled!==undefined&&typeof input.enabled!=='boolean')fail('模板收信开关必须是布尔值。');
const readOnly=input.readOnly===true;
if(!readOnly&&(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100))fail('请填写模板发件人名单,并选择是否启用收信。');
const receiveEnabled=input.receiveEnabled===undefined?(old?.receiveEnabled??true):input.receiveEnabled;if(typeof receiveEnabled!=='boolean')fail('请选择是否启用 IMAP 收信。');
input=require('./account-config.cjs').expandAccount(input,old,address);
const enabled=!readOnly&&receiveEnabled&&input.enabled===true;
if(!readOnly&&(!Array.isArray(input.senders)||input.senders.length>100||(enabled&&!input.senders.length)))fail('请填写模板发件人名单,并选择是否启用收信。');
const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind]?.password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
const saved={name:text(input.name,'邮箱名称',80),email:address,readOnly,smtp:readOnly?{}:endpoint('smtp'),imap:endpoint('imap'),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled:readOnly?false:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
const saved={name:text(input.name,'邮箱名称',80),email:address,readOnly,receiveEnabled,smtp:readOnly?{}:endpoint('smtp'),imap:receiveEnabled?endpoint('imap'):(old?.imap||{}),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
if(input.signature!==undefined)saved.signature=require('./content.cjs').normalizeSignature(input.signature);else if(old?.signature)saved.signature=old.signature;
const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null;
const changed=reset||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
const changed=reset||old?.receiveEnabled!==receiveEnabled||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
this.db.prepare('INSERT INTO channels VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email,version=excluded.version,payload=excluded.payload,state=excluded.state,cursor=excluded.cursor').run(id,address,(old?.version||0)+1,this.encode(id,saved),JSON.stringify(state),reset?'{}':oldrow.cursor);return this.publicChannel(id);
});}
guard(id,version){if(this.row(id).version!==version)fail('邮箱配置已变化,请重试。',409);}
+1 -1
View File
@@ -2,7 +2,7 @@ const {test}=require('node:test');const assert=require('node:assert/strict');con
test('mail management saves a real config, previews template under CSP and confirms after review; narrow layout stays inside viewport',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const mailStore=new MailStore(path.join(dir,'mail')),mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});let browser;
t.after(async()=>{await browser?.close();await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1360,height:950}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#mail');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加邮箱',exact:true}).click({timeout:5000});
await page.getByLabel('邮箱名称',{exact:true}).fill('通知邮箱');await page.getByLabel('邮箱地址',{exact:true}).fill('orders@company.test');for(const type of ['SMTP','IMAP']){await page.getByLabel(type+' 服务器',{exact:true}).fill(type.toLowerCase()+'.company.test');await page.getByLabel(type+' 登录账号',{exact:true}).fill('orders');await page.getByLabel(type+' 密码 / 授权码',{exact:true}).fill('Secret-mail-123');}await page.getByLabel('允许提交模板的发件人',{exact:true}).fill('author@company.test');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('通知邮箱',{exact:true}).waitFor();assert.equal(mailStore.channels().length,1);
await page.getByLabel('邮箱名称',{exact:true}).fill('通知邮箱');await page.getByLabel('邮箱地址',{exact:true}).fill('orders@company.test');await page.getByLabel('启用 IMAP 收信与历史查询',{exact:true}).check();await page.locator('#mail-advanced').evaluate(e=>e.open=true);for(const type of ['SMTP','IMAP']){await page.getByLabel(type+' 服务器',{exact:true}).fill(type.toLowerCase()+'.company.test');await page.getByLabel(type+' 登录账号',{exact:true}).fill('orders');await page.getByLabel(type+' 密码 / 授权码',{exact:true}).fill('Secret-mail-123');}await page.getByLabel('允许提交模板的发件人',{exact:true}).fill('author@company.test');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('通知邮箱',{exact:true}).waitFor();assert.equal(mailStore.channels().length,1);
const c=mailStore.channels()[0],raw=Buffer.from('From: author@company.test\r\nTo: orders@company.test\r\nSubject: [模板]Notice\r\nMIME-Version: 1.0\r\nContent-Type: text/html\r\n\r\n<table><tr><td>Template body</td></tr></table><img src="https://tracker.test/1">');const draft=mailStore.ingest(c.id,'1',1,await parseTemplate(raw,c),raw,1);await page.locator('#sidebar-menu a[data-view=business-settings]').click();await page.getByRole('link',{name:'通知配置',exact:true}).click();await page.locator('#notification-config-tabs').getByRole('link',{name:'邮件模板',exact:true}).click();await page.getByRole('button',{name:'预览并确认',exact:true}).click();await page.frameLocator('iframe[title="邮件正文预览"]').getByText('Template body',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'pending');await page.getByLabel('发信标题',{exact:true}).fill('Confirmed notice');await page.getByRole('button',{name:'确认生效',exact:true}).click();await page.getByText('模板已确认生效。',{exact:true}).waitFor();assert.equal(mailStore.template(draft.id).status,'active');
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
});
+12
View File
@@ -0,0 +1,12 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');const {Store}=require('../../src/modules/dashboard/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');const {parseTemplate}=require('../../src/modules/mail/parser.cjs');
test('unified account defaults to one credential, presets SMTP-only and preserves advanced legacy credentials',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'mail-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const mailStore=new MailStore(path.join(dir,'mail')),mail=new MailService({store:mailStore});const server=createDashboard({store,mail,outputDir:dir});let browser;
t.after(async()=>{await browser?.close();await mail.stop();await new Promise(r=>server.close(r));mailStore.close();fs.rmSync(dir,{recursive:true,force:true});});await new Promise(r=>server.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+server.address().port;browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1360,height:950}});const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/#mail');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加邮箱',exact:true}).click({timeout:5000});
await page.getByLabel('邮箱名称',{exact:true}).fill('统一邮箱');await page.getByLabel('邮箱地址',{exact:true}).fill('notice@163.com');
await page.getByLabel('密码 / 授权码',{exact:true}).fill('shared-secret');assert.equal(await page.getByLabel('SMTP 登录账号',{exact:true}).isVisible(),false);
await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('统一邮箱',{exact:true}).waitFor();
assert.equal(await page.getByText('IMAP 未启用',{exact:true}).count(),1);let c=mailStore.channels()[0];assert.equal(c.smtp.host,'smtp.163.com');assert.equal(c.receiveEnabled,false);assert.equal(c.enabled,false);assert.equal(mailStore.channelSecret(c.id).smtp.password,'shared-secret');
await page.getByRole('button',{name:'管理邮箱',exact:true}).click();await page.getByText('高级设置',{exact:true}).click();await page.getByLabel('SMTP 登录账号',{exact:true}).fill('custom-login');await page.getByLabel('SMTP 密码 / 授权码',{exact:true}).fill('custom-secret');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('统一邮箱',{exact:true}).waitFor();
await page.getByRole('button',{name:'管理邮箱',exact:true}).click();await page.getByLabel('邮箱名称',{exact:true}).fill('改名');await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('改名',{exact:true}).waitFor();const secret=mailStore.channelSecret(c.id);assert.equal(secret.smtp.user,'custom-login');assert.equal(secret.smtp.password,'custom-secret');assert.equal(secret.id,c.id);assert.deepEqual(errors,[]);await page.getByRole('button',{name:'只读查阅已发送邮件',exact:true}).click();await page.locator('#history-channel').waitFor();assert.equal(await page.locator('#history-channel option').count(),1);await page.getByRole('button',{name:'返回邮箱管理',exact:true}).click();await page.getByRole('button',{name:'管理邮箱',exact:true}).click();await page.getByLabel('启用 IMAP 收信与历史查询',{exact:true}).check();await page.getByLabel('密码 / 授权码',{exact:true}).fill('new-shared-secret');assert.equal(await page.locator('#mail-form').evaluate(e=>e.checkValidity()),true);await page.getByRole('button',{name:'保存邮箱',exact:true}).click();await page.getByText('改名',{exact:true}).waitFor();assert.equal(mailStore.channelSecret(c.id).imap.host,'imap.163.com');assert.equal(mailStore.channelSecret(c.id).imap.password,'new-shared-secret');
});
+8
View File
@@ -0,0 +1,8 @@
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path');const {MailStore}=require('../../src/modules/mail/store.cjs');const {MailService}=require('../../src/modules/mail/service.cjs');
function setup(t){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'unified-mail-')),store=new MailStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});return store;}
const legacy={name:'Legacy',email:'old@company.test',enabled:false,senders:['author@company.test'],smtp:{host:'smtp.company.test',port:465,security:'tls',user:'smtp-login',password:'smtp-original'},imap:{host:'imap.company.test',port:993,security:'tls',user:'imap-login',password:'imap-original'}};
test('shared account uses provider presets, optional IMAP and never returns secrets',t=>{const store=setup(t);const c=store.saveChannel({name:'发送',email:'notice@163.com',password:'shared-secret',receiveEnabled:false});assert.equal(c.smtp.host,'smtp.163.com');assert.equal(c.smtp.user,'notice@163.com');assert.equal(c.smtp.port,465);assert.equal(c.receiveEnabled,false);assert.deepEqual(c.senders,[]);assert.equal(c.enabled,false);assert.doesNotMatch(JSON.stringify(c),/shared-secret/);assert.equal(store.channelSecret(c.id).smtp.password,'shared-secret');});
test('blank shared password preserves distinct legacy credentials and identity',t=>{const store=setup(t),c=store.saveChannel(legacy);const updated=store.saveChannel({...c,password:''});const secret=store.channelSecret(c.id);assert.equal(updated.id,c.id);assert.equal(updated.receiveEnabled,true);assert.equal(secret.smtp.password,'smtp-original');assert.equal(secret.imap.password,'imap-original');assert.equal(secret.smtp.user,'smtp-login');assert.equal(secret.imap.user,'imap-login');});
test('enabled receiving uses shared credentials for both protocols without enabling polling',t=>{const store=setup(t),c=store.saveChannel({name:'QQ',email:'123@qq.com',password:'shared-secret',receiveEnabled:true,enabled:false});const s=store.channelSecret(c.id);assert.equal(s.imap.host,'imap.qq.com');assert.equal(s.imap.password,'shared-secret');assert.equal(s.smtp.password,'shared-secret');assert.equal(c.enabled,false);assert.throws(()=>store.saveChannel({...c,password:'',enabled:true}),/发件人/);});
test('SMTP-only check never connects IMAP or sends, and receiving operations are rejected',async t=>{const store=setup(t),old=store.saveChannel(legacy),c=store.saveChannel({...old,receiveEnabled:false,smtp:{...old.smtp,password:''},imap:{...old.imap,password:''}});let checks=0,imapConnections=0;const service=new MailService({store,smtpFactory:()=>({async verify(){checks++;},sendMail(){assert.fail('check must never send');},close(){}}),imapFactory:()=>{imapConnections++;assert.fail('disabled IMAP must never connect');}});t.after(()=>service.stop());const result=await service.verify(c.id);assert.equal(result.state.smtp,true);assert.equal(result.state.imap,false);assert.equal(checks,1);assert.equal(imapConnections,0);await assert.rejects(service.history(c.id,{}),e=>e.status===409);await assert.rejects(service.poll(c.id),e=>e.status===409);});
test('supplied polling switch must be boolean while omission retains SMTP-only defaults',t=>{const store=setup(t);for(const enabled of ['true',null,1])assert.throws(()=>store.saveChannel({name:'invalid',email:'invalid@163.com',password:'secret',receiveEnabled:false,enabled}),/收信|开关/);});
+1 -1
View File
@@ -3,7 +3,7 @@
async function render(container,{api,esc,formatDate,notify,user,isActive=()=>true,back}){
const data=await api('/mail');if(!isActive())return;
if(user.role!=='admin'){container.innerHTML='<div class="alert alert-info">历史邮件仅限管理员查阅。</div>';return;}
const channels=data.channels;
const channels=data.channels.filter(c=>c.receiveEnabled!==false);
container.innerHTML=`<section class="card mb-3"><div class="card-header flex-wrap gap-2"><h2 class="card-title">只读查阅已发送邮件</h2>${back?'<button class="btn btn-sm ms-auto" id="history-back">返回邮箱管理</button>':''}<button class="btn btn-primary" id="history-add">添加只读邮箱</button></div><div class="card-body"><p>用于核对历史通知的主题、正文、主送、抄送和附件名称。只读取服务器上的已发送邮件,不更改已读标记,不发信,不导入模板。</p><div class="text-secondary small">邮箱须开通 IMAP。授权码仅在本机表单填写并加密保存;无需 SMTP 配置。若历史邮件仅保存在 Foxmail 本地,IMAP 无法读取。</div></div></section><div id="history-editor"></div><form class="card" id="history-search"><div class="card-body"><label class="form-label" for="history-channel">查询邮箱</label><div class="d-flex flex-wrap gap-2 mb-3"><select class="form-select" style="max-width:100%" id="history-channel"><option value="">请选择邮箱</option>${channels.map(c=>`<option value="${esc(c.id)}">${esc(c.name)} · ${esc(c.email)}</option>`).join('')}</select><button type="button" class="btn" id="history-folders">连接并列出已发送文件夹</button><button type="button" class="btn" id="history-edit">修改只读邮箱配置</button></div><label class="form-label" for="history-folder">已发送文件夹</label><select class="form-select mb-3" id="history-folder" required><option value="">请先连接邮箱</option></select><div class="row g-3"><div class="col-md-4"><label class="form-label" for="history-since">开始日期(包含)</label><input class="form-control" type="date" id="history-since" required></div><div class="col-md-4"><label class="form-label" for="history-before">结束日期(不包含)</label><input class="form-control" type="date" id="history-before" required></div><div class="col-md-4"><label class="form-label" for="history-subject">主题关键词</label><input class="form-control" id="history-subject" maxlength="100" value="订单"></div></div><div class="form-hint mt-2">每次最多31天,显示最近20封匹配邮件;结果多时缩小日期或关键词。</div><div id="history-error" class="text-danger mt-3" role="alert"></div></div><div class="card-footer"><button class="btn btn-primary" type="submit">查询已发送邮件</button></div></form><div id="history-results" class="mt-3"></div><div id="history-detail" class="mt-3"></div>`;
const find=id=>container.querySelector('#'+id),read=id=>find(id).value;
const day=d=>new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(d);
+8 -3
View File
@@ -11,13 +11,18 @@ window.MailViews=(()=>{
function configure(options){({api,esc,formatDate,notify,user}=options);}
async function accounts(container,isActive=()=>true){
const data=await api('/mail');if(!isActive())return;const admin=user.role==='admin';
container.innerHTML=`<div class="card mb-3"><div class="card-body d-flex flex-wrap align-items-center gap-3"><div><h2 class="card-title mb-1">托管邮箱</h2><div class="text-secondary">SMTP 发信 · IMAP 收信 · 每分钟检查模板邮件</div></div>${admin?'<button class="btn ms-auto" id="mail-history">只读查阅已发送邮件</button><button class="btn btn-primary" id="mail-add">添加邮箱</button>':''}</div></div><div id="mail-editor"></div><div class="row row-cards">${data.channels.filter(c=>!c.readOnly).map(c=>`<div class="col-lg-6"><div class="card h-100"><div class="card-header"><h3 class="card-title">${esc(c.name)}</h3><span class="badge bg-${c.enabled?'blue':'secondary'}-lt ms-auto">${c.enabled?'收信已开启':'收信已暂停'}</span></div><div class="card-body"><div class="fw-medium mb-3">${esc(c.email)}</div><div class="d-flex gap-2 flex-wrap mb-3"><span class="badge bg-${c.state.smtp?'green':'yellow'}-lt">SMTP ${c.state.smtp?'已连接':'待检查'}</span><span class="badge bg-${c.state.imap?'green':'yellow'}-lt">IMAP ${c.state.imap?'已连接':'待检查'}</span></div><div class="text-secondary">${esc(c.state.message)}</div><div class="small text-secondary mt-2">上次检查:${formatDate(c.state.checkedAt)}<br>上次收信:${formatDate(c.state.pollAt)}</div><div class="small mt-3 text-secondary">模板发件人:${esc(c.senders.join('、'))}</div></div>${admin?`<div class="card-footer btn-list"><button class="btn btn-sm" data-edit="${c.id}">管理邮箱</button><button class="btn btn-sm" data-verify="${c.id}">检查连接</button><button class="btn btn-sm btn-primary" data-poll="${c.id}" ${c.enabled?'':'disabled'}>立即收信</button><a class="btn btn-sm" href="#templates">查看模板</a></div>`:''}</div></div>`).join('')||'<div class="col-12"><div class="card card-body text-center text-secondary py-5">尚未添加托管邮箱</div></div>'}</div><div class="card mt-3"><div class="card-body"><h3 class="card-title">用邮件提交模板</h3><p>新建邮件发送到托管邮箱,主题填写 <code>[模板][产品线]发信标题</code>,正文及附件作为模板。省略产品线时使用默认模板。</p><div class="text-secondary">发件人须在允许名单中。首次收取近 7 天邮件,新模板在“邮件模板”中预览确认后生效。</div></div></div><details class="card mt-3"><summary class="card-body cursor-pointer">最近收信记录(${data.receipts.length})</summary><div class="table-responsive"><table class="table card-table"><thead><tr><th>时间 / 邮箱</th><th>结果</th></tr></thead><tbody>${data.receipts.map(r=>`<tr><td class="small">${formatDate(r.at)}<div class="text-secondary">${esc(data.channels.find(c=>c.id===r.channel_id)?.name||'—')}</div></td><td>${esc(r.detail)}</td></tr>`).join('')||'<tr><td colspan="2" class="text-secondary">暂无收信记录</td></tr>'}</tbody></table></div></details>${data.sends.length?`<details class="card mt-3"><summary class="card-body cursor-pointer">测试发信记录</summary><div class="table-responsive"><table class="table card-table"><tbody>${data.sends.map(s=>`<tr><td>${formatDate(s.at)}</td><td>${esc(data.channels.find(c=>c.id===s.channel_id)?.email||'—')}</td><td>${({sent:'已提交至邮件服务器',unknown:'结果待核对',sending:'发送中'})[s.status]||esc(s.status)}</td></tr>`).join('')}</tbody></table></div></details>`:''}`;
container.innerHTML=`<div class="card mb-3"><div class="card-body d-flex flex-wrap align-items-center gap-3"><div><h2 class="card-title mb-1">托管邮箱</h2><div class="text-secondary">SMTP 发信 · IMAP 收信 · 每分钟检查模板邮件</div></div>${admin?'<button class="btn ms-auto" id="mail-history">只读查阅已发送邮件</button><button class="btn btn-primary" id="mail-add">添加邮箱</button>':''}</div></div><div id="mail-editor"></div><div class="row row-cards">${data.channels.filter(c=>!c.readOnly).map(c=>`<div class="col-lg-6"><div class="card h-100"><div class="card-header"><h3 class="card-title">${esc(c.name)}</h3><span class="badge bg-${c.enabled?'blue':'secondary'}-lt ms-auto">${c.enabled?'收信已开启':'收信已暂停'}</span></div><div class="card-body"><div class="fw-medium mb-3">${esc(c.email)}</div><div class="d-flex gap-2 flex-wrap mb-3"><span class="badge bg-${c.state.smtp?'green':'yellow'}-lt">SMTP ${c.state.smtp?'已连接':'待检查'}</span><span class="badge bg-${c.state.imap?'green':'yellow'}-lt">IMAP ${c.receiveEnabled===false?'未启用':c.state.imap?'已连接':'待检查'}</span></div><div class="text-secondary">${esc(c.state.message)}</div><div class="small text-secondary mt-2">上次检查:${formatDate(c.state.checkedAt)}<br>上次收信:${formatDate(c.state.pollAt)}</div><div class="small mt-3 text-secondary">模板发件人:${esc(c.senders.join('、'))}</div></div>${admin?`<div class="card-footer btn-list"><button class="btn btn-sm" data-edit="${c.id}">管理邮箱</button><button class="btn btn-sm" data-verify="${c.id}">检查连接</button><button class="btn btn-sm btn-primary" data-poll="${c.id}" ${c.enabled&&c.receiveEnabled!==false?'':'disabled'}>立即收信</button><a class="btn btn-sm" href="#templates">查看模板</a></div>`:''}</div></div>`).join('')||'<div class="col-12"><div class="card card-body text-center text-secondary py-5">尚未添加托管邮箱</div></div>'}</div><div class="card mt-3"><div class="card-body"><h3 class="card-title">用邮件提交模板</h3><p>新建邮件发送到托管邮箱,主题填写 <code>[模板][产品线]发信标题</code>,正文及附件作为模板。省略产品线时使用默认模板。</p><div class="text-secondary">发件人须在允许名单中。首次收取近 7 天邮件,新模板在“邮件模板”中预览确认后生效。</div></div></div><details class="card mt-3"><summary class="card-body cursor-pointer">最近收信记录(${data.receipts.length})</summary><div class="table-responsive"><table class="table card-table"><thead><tr><th>时间 / 邮箱</th><th>结果</th></tr></thead><tbody>${data.receipts.map(r=>`<tr><td class="small">${formatDate(r.at)}<div class="text-secondary">${esc(data.channels.find(c=>c.id===r.channel_id)?.name||'—')}</div></td><td>${esc(r.detail)}</td></tr>`).join('')||'<tr><td colspan="2" class="text-secondary">暂无收信记录</td></tr>'}</tbody></table></div></details>${data.sends.length?`<details class="card mt-3"><summary class="card-body cursor-pointer">测试发信记录</summary><div class="table-responsive"><table class="table card-table"><tbody>${data.sends.map(s=>`<tr><td>${formatDate(s.at)}</td><td>${esc(data.channels.find(c=>c.id===s.channel_id)?.email||'—')}</td><td>${({sent:'已提交至邮件服务器',unknown:'结果待核对',sending:'发送中'})[s.status]||esc(s.status)}</td></tr>`).join('')}</tbody></table></div></details>`:''}`;
if(!admin)return;container.querySelector('#mail-history').onclick=()=>action(container.querySelector('#mail-history'),()=>window.MailHistoryViews.render(container,{api,esc,formatDate,notify,user,isActive,back:()=>accounts(container,isActive)}));container.querySelector('#mail-add').onclick=()=>editor();
container.querySelectorAll('[data-edit]').forEach(b=>b.onclick=()=>editor(data.channels.find(c=>c.id===b.dataset.edit)));
for(const type of ['verify','poll'])container.querySelectorAll(`[data-${type}]`).forEach(b=>b.onclick=()=>action(b,async()=>{await api(`/mail/channels/${b.dataset[type]}/${type}`,{});if(isActive())await window.PageLifecycle.afterSave(()=>accounts(container,isActive),type==='verify'?'连接检查完成。':'收信检查完成。',notify,isActive);}));
function editor(c){const endpoint=(kind,port)=>{const v=c?.[kind.toLowerCase()]||{host:'',port,security:'tls',user:''};return `<div class="col-lg-6"><fieldset class="form-fieldset"><legend class="float-none w-auto fs-4">${kind}</legend><div class="mb-3"><label class="form-label required" for="${kind}-host">${kind} 服务器</label><input id="${kind}-host" class="form-control" required maxlength="253" placeholder="${kind.toLowerCase()}.company.com" value="${esc(v.host)}"></div><div class="row mb-3"><div class="col-5"><label class="form-label required" for="${kind}-port">${kind} 端口</label><input type="number" min="1" max="65535" id="${kind}-port" class="form-control" required value="${v.port}"></div><div class="col-7"><label class="form-label" for="${kind}-security">${kind} 加密方式</label><select class="form-select" id="${kind}-security"><option value="tls" ${v.security==='tls'?'selected':''}>SSL / TLS</option><option value="starttls" ${v.security==='starttls'?'selected':''}>STARTTLS</option></select></div></div><div class="mb-3"><label class="form-label required" for="${kind}-user">${kind} 登录账号</label><input id="${kind}-user" class="form-control" required maxlength="254" autocomplete="off" value="${esc(v.user)}"></div><div><label class="form-label ${c?'':'required'}" for="${kind}-password">${kind} 密码 / 授权码</label><input id="${kind}-password" type="password" class="form-control" maxlength="2048" autocomplete="new-password" ${c?'':'required'} placeholder="${c?'留空保留已保存密码':'填写邮箱密码或授权码'}"></div></fieldset></div>`;};const host=container.querySelector('#mail-editor');host.innerHTML=`<form class="card mb-3" id="mail-form" autocomplete="off"><div class="card-header"><h3 class="card-title">${c?'管理邮箱':'添加邮箱'}</h3><button class="btn btn-sm ms-auto" type="button" id="mail-cancel">取消</button></div><div class="card-body"><div class="row g-3"><div class="col-md-6"><label class="form-label required" for="mail-name">邮箱名称</label><input id="mail-name" class="form-control" required maxlength="80" value="${esc(c?.name||'')}"></div><div class="col-md-6"><label class="form-label required" for="mail-address">邮箱地址</label><input id="mail-address" type="email" class="form-control" required maxlength="254" value="${esc(c?.email||'')}"></div>${endpoint('SMTP',465)}${endpoint('IMAP',993)}<div class="col-12"><label class="form-label required" for="mail-senders">允许提交模板的发件人</label><textarea id="mail-senders" class="form-control" rows="2" required placeholder="同事邮箱,多个地址用逗号或换行分隔">${esc(c?.senders.join('\n')||'')}</textarea></div><div class="col-12"><hr><h3 class="h4">邮件尾部签名</h3><label class="form-check form-switch mb-3"><input id="mail-signature-enabled" class="form-check-input" type="checkbox" ${c?.signature?.enabled?'checked':''}><span class="form-check-label">启用邮件签名</span></label><label class="form-label" for="mail-signature-format">签名格式</label><select class="form-select mb-3" id="mail-signature-format"><option value="text" ${c?.signature?.format!=='html'?'selected':''}>纯文本</option><option value="html" ${c?.signature?.format==='html'?'selected':''}>HTML</option></select><label class="form-label" for="mail-signature-body">签名内容</label><textarea class="form-control font-monospace" id="mail-signature-body" rows="6" maxlength="50000">${esc(c?.signature?.body||'')}</textarea><div class="form-hint">填写固定署名、联系方式或HTML签名。新批次追加此签名,已冻结邮件不变;模板正文内已有签名请手动调整。</div><button type="button" class="btn btn-sm mt-2" id="mail-signature-preview">预览签名</button><iframe class="mail-preview mt-2" title="邮件签名预览" sandbox hidden></iframe></div><div class="col-12"><label class="form-check form-switch"><input id="mail-enabled" class="form-check-input" type="checkbox" ${c?.enabled?'checked':''}><span class="form-check-label">启用模板收信</span></label><div class="form-hint">可先保存并检查连接,再开启定时收信。公司邮箱需已开通 SMTP 和 IMAP。</div></div></div><div class="text-danger mt-3" id="mail-save-error" role="alert"></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">保存邮箱</button></div></form>`;
function editor(c){const endpoint=(kind,port)=>{const v={host:'',port,security:'tls',user:'',...c?.[kind.toLowerCase()]};return `<div class="col-lg-6"><fieldset class="form-fieldset"><legend class="float-none w-auto fs-4">${kind}</legend><div class="mb-3"><label class="form-label required" for="${kind}-host">${kind} 服务器</label><input id="${kind}-host" class="form-control" required maxlength="253" placeholder="${kind.toLowerCase()}.company.com" value="${esc(v.host)}"></div><div class="row mb-3"><div class="col-5"><label class="form-label required" for="${kind}-port">${kind} 端口</label><input type="number" min="1" max="65535" id="${kind}-port" class="form-control" required value="${v.port}"></div><div class="col-7"><label class="form-label" for="${kind}-security">${kind} 加密方式</label><select class="form-select" id="${kind}-security"><option value="tls" ${v.security==='tls'?'selected':''}>SSL / TLS</option><option value="starttls" ${v.security==='starttls'?'selected':''}>STARTTLS</option></select></div></div><div class="mb-3"><label class="form-label required" for="${kind}-user">${kind} 登录账号</label><input id="${kind}-user" class="form-control" maxlength="254" autocomplete="off" value="${esc(v.user)}"></div><div><label class="form-label ${c?'':'required'}" for="${kind}-password">${kind} 密码 / 授权码</label><input id="${kind}-password" type="password" class="form-control" maxlength="2048" autocomplete="new-password" placeholder="${c?'留空保留已保存密码':'填写邮箱密码或授权码'}"></div></fieldset></div>`;};const host=container.querySelector('#mail-editor');host.innerHTML=`<form class="card mb-3" id="mail-form" autocomplete="off"><div class="card-header"><h3 class="card-title">${c?'管理邮箱':'添加邮箱'}</h3><button class="btn btn-sm ms-auto" type="button" id="mail-cancel">取消</button></div><div class="card-body"><div class="row g-3"><div class="col-md-6"><label class="form-label required" for="mail-name">邮箱名称</label><input id="mail-name" class="form-control" required maxlength="80" value="${esc(c?.name||'')}"></div><div class="col-md-6"><label class="form-label required" for="mail-address">邮箱地址</label><input id="mail-address" type="email" class="form-control" required maxlength="254" value="${esc(c?.email||'')}"></div><div class="col-md-6"><label class="form-label" for="mail-provider">邮箱服务商</label><select id="mail-provider" class="form-select"><option value="">自动识别 / 自定义</option value="163.com">网易 163</option><option value="126.com">网易 126</option><option value="qq.com">QQ / Foxmail</option><option value="yeah.net">网易 Yeah</option></select></div><div class="col-md-6"><label class="form-label" for="mail-password">密码 / 授权码</label><input id="mail-password" type="password" class="form-control" maxlength="2048" autocomplete="new-password" placeholder="${c?'留空分别保留已保存密码':'SMTP 与 IMAP 共用授权码'}"><div class="form-hint">默认使用邮箱地址登录;高级设置可分别配置账号和密码。</div></div><div class="col-12"><label class="form-check form-switch"><input id="mail-receive-enabled" type="checkbox" class="form-check-input" ${c&&c.receiveEnabled!==false?'checked':''}><span class="form-check-label">启用 IMAP 收信与历史查询</span></label></div><div class="col-12"><details id="mail-advanced"><summary class="mb-3 cursor-pointer">高级设置</summary><div class="row g-3">${endpoint('SMTP',465)}${endpoint('IMAP',993)}</div></details></div><div class="col-12"><label class="form-label required" for="mail-senders">允许提交模板的发件人</label><textarea id="mail-senders" class="form-control" rows="2" placeholder="同事邮箱,多个地址用逗号或换行分隔">${esc(c?.senders.join('\n')||'')}</textarea></div><div class="col-12"><hr><h3 class="h4">邮件尾部签名</h3><label class="form-check form-switch mb-3"><input id="mail-signature-enabled" class="form-check-input" type="checkbox" ${c?.signature?.enabled?'checked':''}><span class="form-check-label">启用邮件签名</span></label><label class="form-label" for="mail-signature-format">签名格式</label><select class="form-select mb-3" id="mail-signature-format"><option value="text" ${c?.signature?.format!=='html'?'selected':''}>纯文本</option><option value="html" ${c?.signature?.format==='html'?'selected':''}>HTML</option></select><label class="form-label" for="mail-signature-body">签名内容</label><textarea class="form-control font-monospace" id="mail-signature-body" rows="6" maxlength="50000">${esc(c?.signature?.body||'')}</textarea><div class="form-hint">填写固定署名、联系方式或HTML签名。新批次追加此签名,已冻结邮件不变;模板正文内已有签名请手动调整。</div><button type="button" class="btn btn-sm mt-2" id="mail-signature-preview">预览签名</button><iframe class="mail-preview mt-2" title="邮件签名预览" sandbox hidden></ifram Line truncated
const presets={'163.com':['smtp.163.com','imap.163.com'],'126.com':['smtp.126.com','imap.126.com'],'qq.com':['smtp.qq.com','imap.qq.com'],'foxmail.com':['smtp.qq.com','imap.qq.com'],'yeah.net':['smtp.yeah.net','imap.yeah.net']};
const syncReceive=()=>{const receive=host.querySelector('#mail-receive-enabled').checked;if(receive&&!host.querySelector('#IMAP-host').value){const address=host.querySelector('#mail-address').value.trim(),server=presets[host.querySelector('#mail-provider').value||address.split('@')[1]]?.[1];if(server){host.querySelector('#IMAP-host').value=server;host.querySelector('#IMAP-user').value=address;}else host.querySelector('#mail-advanced').open=true;}for(const node of host.querySelectorAll('[id^="IMAP-"]')){node.disabled=!receive;if(['IMAP-host','IMAP-port'].includes(node.id))node.required=receive;}host.querySelector('#mail-enabled').disabled=!receive;host.querySelector('#mail-senders').required=receive&&host.querySelector('#mail-enabled').checked;};
const preset=()=>{const address=host.querySelector('#mail-address').value.trim(),key=host.querySelector('#mail-provider').value||address.split('@')[1],servers=presets[key];if(servers){for(const [i,kind] of ['SMTP','IMAP'].entries()){host.querySelector('#'+kind+'-host').value=servers[i];host.querySelector('#'+kind+'-port').value=kind==='SMTP'?465:993;host.querySelector('#'+kind+'-security').value='tls';}}else host.querySelector('#mail-advanced').open=true;if(!c)for(const kind of ['SMTP','IMAP'])host.querySelector('#'+kind+'-user').value=address;};
host.querySelector('#mail-provider').onchange=preset;if(!c)host.querySelector('#mail-address').onchange=preset;
host.querySelector('#mail-receive-enabled').onchange=syncReceive;host.querySelector('#mail-enabled').onchange=syncReceive;syncReceive();
host.querySelector('#mail-signature-preview').onclick=event=>action(event.currentTarget,async()=>{const frame=host.querySelector('iframe');await window.MailTemplateEditor.preview(frame,api,{format:host.querySelector('#mail-signature-format').value,body:host.querySelector('#mail-signature-body').value});if(isActive()&&frame.isConnected)frame.hidden=false;});
host.querySelector('#mail-cancel').onclick=()=>host.replaceChildren();host.scrollIntoView({block:'start',behavior:'smooth'});host.querySelector('#mail-form').onsubmit=async event=>{event.preventDefault();const button=event.submitter;button.disabled=true;host.querySelector('#mail-save-error').textContent='';try{const read=id=>host.querySelector('#'+id).value;const connection=kind=>({host:read(kind+'-host'),port:Number(read(kind+'-port')),security:read(kind+'-security'),user:read(kind+'-user'),password:read(kind+'-password')});const saved=await api('/mail/channels',{...(c?{id:c.id,version:c.version}:{}),name:read('mail-name'),email:read('mail-address'),smtp:connection('SMTP'),imap:connection('IMAP'),senders:split(read('mail-senders')),signature:{enabled:host.querySelector('#mail-signature-enabled').checked,format:read('mail-signature-format'),body:read('mail-signature-body')},enabled:host.querySelector('#mail-enabled').checked});if(!isActive())return;c=saved;host.querySelectorAll('[type="password"]').forEach(e=>{e.value='';e.required=false;});await window.PageLifecycle.afterSave(()=>accounts(container,isActive),'邮箱已保存。',notify,isActive);}catch(e){if(isActive())host.querySelector('#mail-save-error').textContent=e.message;}finally{if(button.isConnected)button.disabled=false;}};
host.querySelector('#mail-cancel').onclick=()=>host.replaceChildren();host.scrollIntoView({block:'start',behavior:'smooth'});host.querySelector('#mail-form').onsubmit=async event=>{event.preventDefault();const button=event.submitter;button.disabled=true;host.querySelector('#mail-save-error').textContent='';try{const read=id=>host.querySelector('#'+id).value;const connection=kind=>({host:read(kind+'-host'),port:Number(read(kind+'-port')),security:read(kind+'-security'),user:read(kind+'-user'),password:read(kind+'-password')});const saved=await api('/mail/channels',{...(c?{id:c.id,version:c.version}:{}),name:read('mail-name'),email:read('mail-address'),password:read('mail-password'),receiveEnabled:host.querySelector('#mail-receive-enabled').checked,readOnly:c?.readOnly===true,smtp:connection('SMTP'),imap:connection('IMAP'),senders:split(read('mail-senders')),signature:{enabled:host.querySelector('#mail-signature-enabled').checked,format:read('mail-signature-format'),body:read('mail-signature-body')},enabled:host.querySelector('#mail-enabled').checked});if(!isActive())return;c=saved;host.querySelectorAll('[type="password"]').forEach(e=>{e.value='';e.required=false;});await window.PageLifecycle.afterSave(()=>accounts(container,isActive),'邮箱已保存。',notify,isActive);}catch(e){if(isActive())host.querySelector('#mail-save-error').textContent=e.message;}finally{if(button.isConnected)button.disabled=false;}};
}
}
async function templates(container,isActive=()=>true,preferredFilter=null){