Click here to Skip to main content
15,886,026 members
Home / Discussions / ASP.NET
   

ASP.NET

 
AnswerRe: ASP.net postback url problem Pin
jkirkerx5-Aug-19 12:48
professionaljkirkerx5-Aug-19 12:48 
QuestionServer-side Blazor and IE11 Pin
MSBassSinger2-Aug-19 5:57
professionalMSBassSinger2-Aug-19 5:57 
Question.Net Core V2.2 - Sending email or gmail using OAuth2 or secure settings in Gmail in the background without browser auth Pin
jkirkerx1-Aug-19 12:28
professionaljkirkerx1-Aug-19 12:28 
AnswerRe: .Net Core V2.2 - Sending email or gmail using OAuth2 or secure settings in Gmail in the background without browser auth Pin
Afzaal Ahmad Zeeshan1-Aug-19 14:37
professionalAfzaal Ahmad Zeeshan1-Aug-19 14:37 
GeneralRe: .Net Core V2.2 - Sending email or gmail using OAuth2 or secure settings in Gmail in the background without browser auth Pin
jkirkerx2-Aug-19 6:50
professionaljkirkerx2-Aug-19 6:50 
GeneralRe: .Net Core V2.2 - Sending email or gmail using OAuth2 or secure settings in Gmail in the background without browser auth Pin
jkirkerx2-Aug-19 11:45
professionaljkirkerx2-Aug-19 11:45 
AnswerThought I had it, Failed to open browser when running in Docker Container Pin
jkirkerx2-Aug-19 12:50
professionaljkirkerx2-Aug-19 12:50 
AnswerFigured it out [solved] Pin
jkirkerx3-Aug-19 13:44
professionaljkirkerx3-Aug-19 13:44 
There are so many caveats to using a gmail account to just send email.

To the best of my knowledge from what I have learned, if you have a free gmail account, you have to use OAuth2 with clientId and use the browser to authenticate. That's the price of free!

If you have a domain verified Gmail account or Google Cloud account that you pay for; you need service account credentials to use that Gmail account to send email. But with this account type you can access the other services available as well such as Calendar, Drive. $6 a month for each account.

I have the latter paid account, a domain verified Google Cloud account, so I had to create service account credentials, then acquire API permission to the Gmail Service, and then go back to my Google Cloud account and go to security, advanced and set the API permissions to the projectId and service scope for sending email using Gmail. Here you can assign various scopes to the API's you selected to subscribe to. This is the key part or else you get strange errors.

Last I had to write different code and use different form of authentication to get a token and send email.
So I wrote a PFX version to send email, which will be obsolete soon, so now I have to write a Json version to replace it next.

I just tested my prototype code in a production version Docker container on my development machine (Docker for Windows - Linux Container) and it works fine so far, email sent in the background without browser authentication and no token written to the project that I can see. I just tested it in a Linux Docker container running on the production server and the message sent.

It's too bad that the internet is polluted with old documentation and misinformation.
The previous help in this thread was helpful, but was targeted towards the free Gmail Account and didn't work in a Docker container. I have achieved the desired result now but I need to go back and refactor the whole thing to clean it up.

This is the new unrefactored code, which is already obsolete because I'm using a straight P12 certificate that is replaced with consuming the JSON P12 file that has the certificate in it.

Note: the password is really the password for the certificate.
public static async Task<ServiceAccountCredential> Create_GoogleCredentialsWithAccessToken(MAILSERVER ms)
{
    var certBuffer = File.ReadAllBytes("projectName-xxxxxxxxxx.p12");
    var certificate = new X509Certificate2(certBuffer, "notasecret", X509KeyStorageFlags.Exportable);
    var serviceAccountEmail = "xxxxxxxxxx-xxxxxx.iam.gserviceaccount.com";
    var userAccountEmail = "xxx@xxxxxx.com";
    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        User = userAccountEmail,
        Scopes = new[] { GmailService.Scope.MailGoogleCom }
    }.FromCertificate(certificate));

    if (await credential.RequestAccessTokenAsync(CancellationToken.None))
    {
        var service = new GmailService(
            new Google.Apis.Services.BaseClientService.Initializer()
            {
                HttpClientInitializer = credential
            }
        );
    }

    return credential;
}
public static async Task<SendEmailCompletedEventArgs> Send_GmailServiceAsync(ServiceAccountCredential serviceCredentials, MimeMessage message, int retryCount)
{
    var currentTry = 0;
    while ((currentTry < retryCount))
    {
        try
        {
            using (var client = new SmtpClient())
            {
                client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                var oauth2 = new SaslMechanismOAuth2(serviceCredentials.User, serviceCredentials.Token.AccessToken);
                client.Authenticate(oauth2);

                await client.SendAsync(message);
                client.Disconnect(true);
            }

            return new SendEmailCompletedEventArgs(null, false, null, currentTry);
        }
        catch (Exception ex)
        {
            currentTry++;
            if ((currentTry >= retryCount))
            {
                return new SendEmailCompletedEventArgs(ex, true, null, currentTry);
            }
        }

    }

    //  Code should never reach here, but without this line you'll get a BC42105 warning:
    return new SendEmailCompletedEventArgs(null, true, null, currentTry);
}
I used the MimeKit to create my message, then I called the function to authenticate and send.
using (var credentials = SendGmailServiceP12Async.Create_GoogleCredentialsWithAccessToken(ms))
{
    var result = await SendGmailServiceP12Async.Send_GmailServiceAsync(await credentials, message, 5);
    SendGmailServiceP12Async.ProcessSendResult(model, result);
}

This is valuable info that should be written up professionally and posted here at Code Project.
I need to rewrite this in the new format first and dial it in, before considering posting an article.
If it ain't broke don't fix it
Discover my world at jkirkerx.com


modified 3-Aug-19 19:59pm.

GeneralRe: Figured it out [solved] - New Code Pin
jkirkerx5-Aug-19 13:22
professionaljkirkerx5-Aug-19 13:22 
QuestionInsert Date Interval Pin
Bartt_dmr25-Jul-19 10:31
Bartt_dmr25-Jul-19 10:31 
AnswerRe: Insert Date Interval Pin
Richard Deeming25-Jul-19 10:49
mveRichard Deeming25-Jul-19 10:49 
QuestionObject reference not set to an instance of an object. Pin
Darwin Ahmed21-Jul-19 12:06
Darwin Ahmed21-Jul-19 12:06 
AnswerRe: Object reference not set to an instance of an object. Pin
phil.o21-Jul-19 19:50
professionalphil.o21-Jul-19 19:50 
AnswerRe: Object reference not set to an instance of an object. Pin
ZurdoDev24-Jul-19 9:10
professionalZurdoDev24-Jul-19 9:10 
QuestionChange Value of HttpContext.Current.User Pin
MadDashCoder21-Jul-19 4:26
MadDashCoder21-Jul-19 4:26 
AnswerRe: Change Value of HttpContext.Current.User Pin
Richard MacCutchan21-Jul-19 6:42
mveRichard MacCutchan21-Jul-19 6:42 
AnswerRe: Change Value of HttpContext.Current.User Pin
Afzaal Ahmad Zeeshan21-Jul-19 6:51
professionalAfzaal Ahmad Zeeshan21-Jul-19 6:51 
AnswerRe: Change Value of HttpContext.Current.User Pin
ZurdoDev24-Jul-19 9:12
professionalZurdoDev24-Jul-19 9:12 
QuestionQuery timing out, help please!!! Pin
samflex19-Jul-19 8:38
samflex19-Jul-19 8:38 
AnswerRe: Query timing out, help please!!! Pin
ZurdoDev19-Jul-19 10:14
professionalZurdoDev19-Jul-19 10:14 
AnswerRe: Query timing out, help please!!! Pin
David Mujica22-Jul-19 7:59
David Mujica22-Jul-19 7:59 
QuestionForm Designer Pin
wrightyrx715-Jul-19 4:58
wrightyrx715-Jul-19 4:58 
AnswerRe: Form Designer Pin
Mycroft Holmes15-Jul-19 11:26
professionalMycroft Holmes15-Jul-19 11:26 
GeneralRe: Form Designer Pin
wrightyrx715-Jul-19 11:33
wrightyrx715-Jul-19 11:33 
GeneralRe: Form Designer Pin
Mycroft Holmes15-Jul-19 14:08
professionalMycroft Holmes15-Jul-19 14:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.