我正在尝试使用Gmail API代表当前经过身份验证的用户发送邮件。
验证
/// <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);
}
}
发送邮件:
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();
这可以找到,但我被迫硬编码用户的电子邮件地址。如何找到已登录用户的电子邮件地址?
答案 0 :(得分:0)
Gmail api有一种方法可让您获取有关您已登录用户的信息。
Users: getProfile获取当前用户的Gmail个人资料。
{
"emailAddress": string,
"messagesTotal": integer,
"threadsTotal": integer,
"historyId": unsigned long
}
通过添加以下请求,我可以获得有关我的用户的信息。
var me = serviceGmail.Users.GetProfile("me").Execute();