问题
I am trying to use the Gmail API to send a mail on behalf of the current authenticated user.
authentication:
/// <summary>
/// This method requests Authentcation from a user using Oauth2.
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <returns>DriveService used to make requests against the Drive API</returns>
public static GmailService AuthenticateOauthGmail(string clientSecretJson, string userName)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
string[] scopes = new string[] { GmailService.Scope.GmailSettingsSharing, //Manage your sensitive mail settings, including who can manage your mail
GmailService.Scope.GmailSettingsBasic, //Manage your basic mail settings
GmailService.Scope.GmailReadonly, //View your emails messages and settings
GmailService.Scope.GmailCompose, //Manage drafts and send emails
GmailService.Scope.GmailInsert, //Insert mail into your mailbox
GmailService.Scope.GmailLabels, //Manage mailbox labels
GmailService.Scope.GmailModify, //View and modify but not delete your email
GmailService.Scope.GmailSend, //Send email on your behalf
GmailService.Scope.MailGoogleCom}; //View and manage your mail
UserCredential credential;
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
return new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Gmail Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
Console.WriteLine("Create Oauth2 account GmailService failed" + ex.Message);
throw new Exception("CreateServiceAccountGmailFailed", ex);
}
}
Send mail:
var msg = new AE.Net.Mail.MailMessage
{
Subject = "Email Subject",
From = new MailAddress("MyUsersEmailAddress","Linda Lawton"),
Body = "The message"
};
msg.To.Add(new MailAddress("SendMailto@test.com", "Linda Lawton"));
msg.ReplyTo.Add(msg.From);
var msgStr = new StringWriter();
msg.Save(msgStr);
var gmailMessage = new Message
{
Raw = Base64UrlEncode(msgStr.ToString())
};
var response = serviceGmail.Users.Messages.Send(gmailMessage, "me").Execute();
This works find but I am forced to have hard coded the users email address. How can I find the email address of the user who has logged in?
回答1:
The Gmail api has a method which allows you to get information about the user you have logged in.
Users: getProfile Gets the current user's Gmail profile.
{
"emailAddress": string,
"messagesTotal": integer,
"threadsTotal": integer,
"historyId": unsigned long
}
By adding the following request I can get the information about my user.
var me = serviceGmail.Users.GetProfile("me").Execute();
来源:https://stackoverflow.com/questions/42783192/how-to-get-my-email-address-from-credentials-or-authorization