diff --git a/src/modules/mail/account-config.cjs b/src/modules/mail/account-config.cjs
new file mode 100644
index 0000000..bbe68b6
--- /dev/null
+++ b/src/modules/mail/account-config.cjs
@@ -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};
diff --git a/src/modules/mail/service.cjs b/src/modules/mail/service.cjs
index a78868a..90a2991 100644
--- a/src/modules/mail/service.cjs
+++ b/src/modules/mail/service.cjs
@@ -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};
diff --git a/src/modules/mail/store.cjs b/src/modules/mail/store.cjs
index 4255ad4..f75e570 100644
--- a/src/modules/mail/store.cjs
+++ b/src/modules/mail/store.cjs
@@ -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);}
diff --git a/tests/mail/mail-ui.test.cjs b/tests/mail/mail-ui.test.cjs
index bf6704c..f9727e2 100644
--- a/tests/mail/mail-ui.test.cjs
+++ b/tests/mail/mail-ui.test.cjs
@@ -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
');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,[]);
});
diff --git a/tests/mail/unified-account-ui.test.cjs b/tests/mail/unified-account-ui.test.cjs
new file mode 100644
index 0000000..99a35d0
--- /dev/null
+++ b/tests/mail/unified-account-ui.test.cjs
@@ -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');
+});
diff --git a/tests/mail/unified-account.test.cjs b/tests/mail/unified-account.test.cjs
new file mode 100644
index 0000000..9679f8a
--- /dev/null
+++ b/tests/mail/unified-account.test.cjs
@@ -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}),/收信|开关/);});
diff --git a/web/modules/mail/history.js b/web/modules/mail/history.js
index 71112c3..eecd996 100644
--- a/web/modules/mail/history.js
+++ b/web/modules/mail/history.js
@@ -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='历史邮件仅限管理员查阅。
';return;}
- const channels=data.channels;
+ const channels=data.channels.filter(c=>c.receiveEnabled!==false);
container.innerHTML=`用于核对历史通知的主题、正文、主送、抄送和附件名称。只读取服务器上的已发送邮件,不更改已读标记,不发信,不导入模板。
邮箱须开通 IMAP。授权码仅在本机表单填写并加密保存;无需 SMTP 配置。若历史邮件仅保存在 Foxmail 本地,IMAP 无法读取。
`;
const find=id=>container.querySelector('#'+id),read=id=>find(id).value;
const day=d=>new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(d);
diff --git a/web/modules/mail/view.js b/web/modules/mail/view.js
index 25b9c3d..f3482d3 100644
--- a/web/modules/mail/view.js
+++ b/web/modules/mail/view.js
@@ -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=`托管邮箱
SMTP 发信 · IMAP 收信 · 每分钟检查模板邮件
${admin?'
':''}
${data.channels.filter(c=>!c.readOnly).map(c=>`
${esc(c.email)}
SMTP ${c.state.smtp?'已连接':'待检查'}IMAP ${c.state.imap?'已连接':'待检查'}
${esc(c.state.message)}
上次检查:${formatDate(c.state.checkedAt)}
上次收信:${formatDate(c.state.pollAt)}
模板发件人:${esc(c.senders.join('、'))}
${admin?``:''}
`).join('')||'
'}
用邮件提交模板
新建邮件发送到托管邮箱,主题填写 [模板][产品线]发信标题,正文及附件作为模板。省略产品线时使用默认模板。
发件人须在允许名单中。首次收取近 7 天邮件,新模板在“邮件模板”中预览确认后生效。
最近收信记录(${data.receipts.length})
| 时间 / 邮箱 | 结果 |
${data.receipts.map(r=>`| ${formatDate(r.at)} ${esc(data.channels.find(c=>c.id===r.channel_id)?.name||'—')} | ${esc(r.detail)} |
`).join('')||'| 暂无收信记录 |
'}
${data.sends.length?`测试发信记录
${data.sends.map(s=>`| ${formatDate(s.at)} | ${esc(data.channels.find(c=>c.id===s.channel_id)?.email||'—')} | ${({sent:'已提交至邮件服务器',unknown:'结果待核对',sending:'发送中'})[s.status]||esc(s.status)} |
`).join('')}
`:''}`;
+ container.innerHTML=`托管邮箱
SMTP 发信 · IMAP 收信 · 每分钟检查模板邮件
${admin?'
':''}
${data.channels.filter(c=>!c.readOnly).map(c=>`
${esc(c.email)}
SMTP ${c.state.smtp?'已连接':'待检查'}IMAP ${c.receiveEnabled===false?'未启用':c.state.imap?'已连接':'待检查'}
${esc(c.state.message)}
上次检查:${formatDate(c.state.checkedAt)}
上次收信:${formatDate(c.state.pollAt)}
模板发件人:${esc(c.senders.join('、'))}
${admin?``:''}
`).join('')||'
'}
用邮件提交模板
新建邮件发送到托管邮箱,主题填写 [模板][产品线]发信标题,正文及附件作为模板。省略产品线时使用默认模板。
发件人须在允许名单中。首次收取近 7 天邮件,新模板在“邮件模板”中预览确认后生效。
最近收信记录(${data.receipts.length})
| 时间 / 邮箱 | 结果 |
${data.receipts.map(r=>`| ${formatDate(r.at)} ${esc(data.channels.find(c=>c.id===r.channel_id)?.name||'—')} | ${esc(r.detail)} |
`).join('')||'| 暂无收信记录 |
'}
${data.sends.length?`测试发信记录
${data.sends.map(s=>`| ${formatDate(s.at)} | ${esc(data.channels.find(c=>c.id===s.channel_id)?.email||'—')} | ${({sent:'已提交至邮件服务器',unknown:'结果待核对',sending:'发送中'})[s.status]||esc(s.status)} |
`).join('')}
`:''}`;
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 ``;};const host=container.querySelector('#mail-editor');host.innerHTML=``;
+ function editor(c){const endpoint=(kind,port)=>{const v={host:'',port,security:'tls',user:'',...c?.[kind.toLowerCase()]};return ``;};const host=container.querySelector('#mail-editor');host.innerHTML=``;
+ 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){