我得到了此代码,该代码从我的帐户获取电子邮件。这适用于我们的自动化流程之一。但是使用另一个帐户无法获得服务错误
private static GmailService GetGmailService()
{
string credPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
UserCredential credential;
using (var stream =
new FileStream(Path.Combine(credPath, "credentials.json"), FileMode.Open, FileAccess.Read))
{
var path = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
var credPath2 = Path.Combine(path, ".credentials/gmail-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath2, true)).Result;
}
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
return service;
}
public static string GetRegistrationLink(string devEmail, string toEmail, string subjectSearch = "", string keywords = "")
{
var url = string.Empty;
var service = GetGmailService();
var inboxlistRequest = service.Users.Messages.List(devEmail);
inboxlistRequest.LabelIds = "INBOX";
var query = @"in:unread in:inbox subject:Reset your CS Professional Suite Web account password";
//@"in:unread ";
//if (!string.IsNullOrEmpty(subjectSearch))
// query += $"subject:{subjectSearch} ";
//if (!string.IsNullOrEmpty(toEmail))
// query += $"to:{toEmail} ";
//if (!string.IsNullOrEmpty(keywords))
// query += $@"{keywords}";
//inboxlistRequest.Q = query;
inboxlistRequest.IncludeSpamTrash = false;
//get our emails
var emailListResponse = inboxlistRequest.Execute();
if (emailListResponse != null && emailListResponse.Messages != null)
{
//loop through each email and get what fields you want...
foreach (var email in emailListResponse.Messages)
{
var emailInfoRequest = service.Users.Messages.Get(devEmail, email.Id);
var emailInfoResponse = emailInfoRequest.Execute();
if (emailInfoResponse == null) continue;
var from = "";
var date = "";
foreach (var mParts in emailInfoResponse.Payload.Headers)
{
switch (mParts.Name)
{
case "Date":
date = mParts.Value;
break;
case "From":
@from = mParts.Value;
break;
}
if (date == "" || @from == "") continue;
var messageBodyParts = emailInfoResponse.Payload?.Parts?.SelectMany(a => a.Parts).ToList();
if (messageBodyParts == null) continue;
foreach (var p in messageBodyParts)
{
if (p.MimeType != "text/html") continue;
byte[] data = FromBase64ForUrlString(p.Body.Data);
var decodedString = Encoding.UTF8.GetString(data);
url = Regex.Match(decodedString, "href\\s*=\\s*\"(?<url>.*?)\"").Groups["url"].Value;
}
}
}
}
return url;
}
已启用api,并且凭据已包含在项目中,但它返回503服务不可用错误。但是当我在控制台上运行相同的代码时,使用相同的凭据即可正常工作。json