如何在web.api

时间:2016-03-09 16:27:40

标签: c# web-services email google-app-engine oauth-2.0

我尝试使用GMAIL OAuth协议发送电子邮件,但GoogleWebAuthorizationBroker.AuthorizeAsync方法挂起。

我尝试从服务器运行它(它是一个web.api项目,通过htttp POST从客户端接收发送电子邮件信息,然后我的服务应该连接到谷歌Gmail并发送电子邮件)然后服务充当Gmail与客户之间的代理。

我从谷歌控制台获取Web客户端的秘密内容。

我使用Visual Studio 2013 C#NET4.5。该服务可以访问我存储DataStore的目录。

我使用的代码如下,并挂在GoogleWebAuthorizationBroker.AuthorizeAsync

DbGoogleDataStore与Google的DataStore实现相同(我计划将来在数据库中创建我的数据存储,因为我将其分开)

 public void SendMailUsingOauthProtocol(SmtpConfigurationSettings settings, SmtpSendMessageInputModel filter)
    {
        var msg = new AE.Net.Mail.MailMessage() // MailMessage
        {

            Subject = filter.Subject,
            Body = filter.Body64,
            From = new MailAddress(settings.Username),
        };
        msg.To.Add(new MailAddress(filter.To));
        msg.ReplyTo.Add(new MailAddress(filter.To));
        var msgStr = new StringWriter();
        msg.Save(msgStr);


        // Get from settings the Client secret
        MemoryStream stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(settings.AutClientSecret);
        writer.Flush();
        stream.Position = 0;
        //ClientSecrets secret = GoogleClientSecrets.Load(stream).Secrets;


        var storeFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
        storeFilePath = storeFilePath + @"\GmailOauth\";
        Debug.WriteLine(storeFilePath);

        IDataStore fileStore = DbGoogleDataStore.Factory(storeFilePath, true);

        // Create the credential.. this step go authenticate with the user if it is necessary
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                stream,
                Scopes,
                "user",
                CancellationToken.None,
                fileStore
                ).Result;

        //Create GMAIL API Service
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName

        });

        var result = service.Users.Messages.Send(new Message { Raw = Base64UrlEncode(msgStr.ToString()) }, "me").Execute();

    }

拜托,有人知道如何做到这一点?

0 个答案:

没有答案