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

使用OAuth2与smtp.gmail发送邮件(C#):认证问题解决

基于Gmail API的邮件发送实现(OAuth2认证,无App Passwords)

需要发送简单邮件,采用认证方式,无法使用App Passwords。此前的难点在于获取授权后的响应,以及确定何时生成邮件,已知发送邮件需使用密码和认证用户身份。

已完成的操作步骤

步骤1:从文件读取凭据

ClientSecrets varClientSecrets = new ClientSecrets();
 
UserCredential credential;

using (var stream =
       new FileStream(pathFile, FileMode.Open, FileAccess.Read,FileShare.Read))
{
    varClientSecrets = GoogleClientSecrets.FromStream(stream).Secrets;
    
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        varClientSecrets,
        new[] { "email", "profile", "https://mail.google.com/" },
        "use",
        CancellationToken.None,
        new FileDataStore(credPath, true)                        
        ).Result;

    strCLIENT_ID = varClientSecrets.ClientId;
    strCLIENT_SECRET = varClientSecrets.ClientSecret;
}

// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer
{
    HttpClientInitializer = credential,
    ApplicationName = "XXX"
});

步骤2:获取凭据数据

// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

ConsultaWeb CW = new ConsultaWeb();
IRestResponse irrRetornoServidor = null;

strSCOPE = credential.Token.Scope;
 
strREDIRECT_URI = "https://accounts.google.com/o/oauth2/v2/auth";

strTokenURL = "https://www.googleapis.com/oauth2/v4/token"; 

/// model: {Authorization: token_type base64(userEmail:userPassword)}

strHeader = "Authorization: " + credential.Token.TokenType + " " 
    + Base64.EncodeToBase64(userEmail + ":" + userPassword);


strURL = "https://accounts.google.com/o/oauth2/v2/auth"
   + "?scope=" + strSCOPE
   + "&access_type=offline"
   + "&include_granted_scopes=true"
   + "&response_type=code"
   + "&state=state_parameter_passthrough_value"
   + "&redirect_uri=" + strREDIRECT_URI
   + "&client_id=" + strCLIENT_ID;
   
strServidorRetorno = CW.RequisicaoWebREST(strURL, GET, JSON
    , out irrRetornoServidor, "", "", "", "", strHeader);

// Return from OAuth 2.0 server
// OAuth 2.0 server responds to your application's access request
// using the URL specified in the request.

////If the user approves the access request, the response
//will contain an authorization code. If the user does not approve the request,
//the response will contain an error message.

//The authorization code or error message that is returned to the web server
//appears on the query string, as shown below:

strAuthCode = "";

步骤3:获取服务器响应

if ((short)irrRetornoServidor.StatusCode == (short)RegrasGlobais.HTTPStatusCode.OK)
{
    if (irrRetornoServidor.ResponseUri.AbsolutePath.Contains("error"))
    {
        // An error response: 
        // https://oauth2.example.com/auth?error=access_denied
        return -1;
    }
    else if (irrRetornoServidor.ResponseUri.AbsolutePath.Contains("ServiceLogin"))
    {
        //An authorization code response
        // https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
        // strAuthCode = "P7q7W91a-oMsCeLvIaQm6bTrgtp7";
        // how to get the autorization response, if this open in  the browser
        strAuthCode = irrRetornoServidor.ResponseUri.Query.ToString();
        
    }

}
else
{
    return -1;
}

步骤4:发送邮件(待完成)

// Gmail API server address
//MailMessage msg = new MailMessage();
// build mail

目前已解决发送邮件前的认证问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:15:38