You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Salesforce Apex或LWC中获取代登录用户的邮箱ID?

获取代登录用户(Manager_A)邮箱的方案

方法一:通过Apex类查询

当使用「以其他用户身份登录」功能时,系统生成的AuthSession记录中,UserId对应被登录的用户(Payee_A),CreatedById则是发起代登录的用户(Manager_A)。基于这个特性,可通过Apex查询获取目标邮箱:

Apex代码示例

public with sharing class ImpersonationUserController {
    @AuraEnabled(cacheable=true)
    public static String getImpersonatingUserEmail() {
        // 查询当前用户的活跃会话
        AuthSession currentSession = [
            SELECT CreatedById 
            FROM AuthSession 
            WHERE UserId = :UserInfo.getUserId() 
            AND IsCurrent = true 
            LIMIT 1
        ];
        
        // 验证是否为代登录场景,查询发起用户的邮箱
        if(currentSession != null && currentSession.CreatedById != UserInfo.getUserId()) {
            User impersonatingUser = [
                SELECT Email 
                FROM User 
                WHERE Id = :currentSession.CreatedById 
                LIMIT 1
            ];
            return impersonatingUser.Email;
        }
        // 非代登录场景返回null
        return null;
    }
}

方法二:在LWC中调用Apex获取

在LWC组件里调用上述Apex方法,即可拿到Manager_A的邮箱:

LWC代码示例

import { LightningElement, wire } from 'lwc';
import getImpersonatingUserEmail from '@salesforce/apex/ImpersonationUserController.getImpersonatingUserEmail';

export default class ImpersonationUserEmail extends LightningElement {
    impersonatingEmail;
    error;

    @wire(getImpersonatingUserEmail)
    wiredImpersonatingUser({ error, data }) {
        if (data) {
            this.impersonatingEmail = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.impersonatingEmail = undefined;
        }
    }
}

注意事项

  • 需确保被登录用户(Payee_A)拥有AuthSession对象的查询权限,以及查看代登录用户(Manager_A)记录的权限
  • 非代登录场景下,方法会返回null,可在LWC中做相应空值处理

内容的提问来源于stack exchange,提问作者R_M_R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:03:11