Smtpclient with Gmail

SmtpClient with Gmail

Try running this:

mozroots --import --ask-remove

in your system (just in bash or from Mono Command Prompt if it is on Windows). And then run the code again.

EDIT:

I forgot you also should run

certmgr -ssl smtps://smtp.gmail.com:465

(and answer yes on questions). This works for me on Mono 2.10.8, Linux (with your example).

C# sending email via Gmail account

If your Gmail account has 2-Step Verification enabled you will have to create an App-Specific Password to authenticate with instead.

Note also that SmtpClient is IDisposable - you should be putting it in a using (var smtpClient = new SmtpClient("smtp.gmail.com", 587)) { ... } block so that the SMTP connection RSETs, QUITs and closes correctly.

== edit ==

Also, it appears you have the from and recipients parameters switched around on smtpClient.Send.

string body = "<head>" +
"Here comes some logo" +
"</head>" +
"<body>" +
"<h1>Account confirmation reqest.</h1>" + Environment.NewLine +
"<a>Dear User, </a>" + Environment.NewLine +
"<a>In order to be able to use musicshop app properly, we require You to confirm Your email address.</a>" + Environment.NewLine +
"<a>This is the last step towards using our app.</a>" + Environment.NewLine +
"<a>Pleas follow this hyperlink to confirm your address.</a>" + Environment.NewLine +
"<a>[Callback url]</a>" +
"</body>";
try
{
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential()
{
UserName = Config.Username,
Password = Config.Password,
};
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;

//Oops: from/recipients switched around here...
//smtpClient.Send("targetemail@targetdomain.xyz", "myemail@gmail.com", "Account verification", body);
smtpClient.Send("myemail@gmail.com", "targetemail@targetdomain.xyz", "Account verification", body);
}
}
catch (Exception e)
{
Console.Error.WriteLine("{0}: {1}", e.ToString(), e.Message);
}

Using SmtpClient to send an email from Gmail

You need to allow "less secure apps":

https://support.google.com/accounts/answer/6010255

Code:

try
{
new SmtpClient
{
Host = "Smtp.Gmail.com",
Port = 587,
EnableSsl = true,
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("MyMail@Gmail.com", "MyPassword")
}.Send(new MailMessage {From = new MailAddress("MyMail@Gmail.com", "MyName"), To = {"TheirMail@Mail.com"}, Subject = "Subject", Body = "Message", BodyEncoding = Encoding.UTF8});
erroremail.Text = "Email has been sent successfully.";
}
catch (Exception ex)
{
erroremail.Text = "ERROR: " + ex.Message;
}

How do I send an email with Gmail and SmtpClient when the sending account uses two factor authentication?

If I understand you correctly, you're saying the Google account is using two-factor authentication.

If that's the case, you need to create an Application Password for this. Go to https://security.google.com/settings/security/apppasswords once logged in as the account you want to two-factor auth with.

In the list, under Select App choose "Other" and give it some name. Click Generate, and write this password DOWN cause you will only ever see it ONCE. You will use this in your authentication. It will be 16-characters long and the spaces don't matter, you can include them or omit them. I included them here just because.

NetworkCredential basicCredential =
new NetworkCredential("sender@gmail.com", "cadf afal rqcf cafo");
MailMessage message = new MailMessage();

Sending email through Gmail SMTP server with C#

CVertex, make sure to review your code, and, if that doesn't reveal anything, post it. I was just enabling this on a test ASP.NET site I was working on, and it works.

Actually, at some point I had an issue on my code. I didn't spot it until I had a simpler version on a console program and saw it was working (no change on the Gmail side as you were worried about). The below code works just like the samples you referred to:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Net;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
}
}

I also got it working using a combination of web.config, http://msdn.microsoft.com/en-us/library/w355a94k.aspx and code (because there is no matching EnableSsl in the configuration file :( ).

2021 Update

By default you will also need to enable access for "less secure apps" in your gmail settings page: google.com/settings/security/lesssecureapps. This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. – thanks to @Ravendarksky

Send smtp gmail email ''Failure sending mail''

I think this will more helpfull to you
https://support.google.com/a/answer/176600?hl=en

SmtpClient in C# using smtp.Gmail.com:857 with Google's 2 Step Verification activated

I've tried to work with the Google API for mail sending before. My understanding is that you have to establish a login (Which will trigger the two step) which provides you with an open session. And then with that open session you can send the mail. Otherwise most likely the code is timing out while waiting for the second half of the login.

Update: You can use the Server Side Authentication process, this will require a one time sign in from the end user (Which will have to go through the sign in with two factor authentication) and that will provide you with a refresh token that can use to re-connect to the server. The information is located at the Google Developers Docs

Excerpt Below

Implementing Server-Side Authorization

Requests to the Gmail API must be authorized using OAuth 2.0
credentials. You should use server-side flow when your application
needs to access Google APIs on behalf of the user, for example when
the user is offline. This approach requires passing a one-time
authorization code from your client to your server; this code is used
to acquire an access token and refresh tokens for your server.

Below is also the sample python code from the site (I know you're using C#)

Replace CLIENTSECRETS_LOCATION value with the location of your client_secrets.json file.

import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from apiclient.discovery import build
# ...

# Path to client_secrets.json which should contain a JSON document such as:
# {
# "web": {
# "client_id": "[[YOUR_CLIENT_ID]]",
# "client_secret": "[[YOUR_CLIENT_SECRET]]",
# "redirect_uris": [],
# "auth_uri": "https://accounts.google.com/o/oauth2/auth",
# "token_uri": "https://accounts.google.com/o/oauth2/token"
# }
# }
CLIENTSECRETS_LOCATION = '<PATH/TO/CLIENT_SECRETS.JSON>'
REDIRECT_URI = '<YOUR_REGISTERED_REDIRECT_URI>'
SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
# Add other requested scopes.
]

class GetCredentialsException(Exception):
"""Error raised when an error occurred while retrieving credentials.

Attributes:
authorization_url: Authorization URL to redirect the user to in order to
request offline access.
"""

def __init__(self, authorization_url):
"""Construct a GetCredentialsException."""
self.authorization_url = authorization_url

class CodeExchangeException(GetCredentialsException):
"""Error raised when a code exchange has failed."""

class NoRefreshTokenException(GetCredentialsException):
"""Error raised when no refresh token has been found."""

class NoUserIdException(Exception):
"""Error raised when no user ID could be retrieved."""

def get_stored_credentials(user_id):
"""Retrieved stored credentials for the provided user ID.

Args:
user_id: User's ID.
Returns:
Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
Raises:
NotImplemented: This function has not been implemented.
"""
# TODO: Implement this function to work with your database.
# To instantiate an OAuth2Credentials instance from a Json
# representation, use the oauth2client.client.Credentials.new_from_json
# class method.
raise NotImplementedError()

def store_credentials(user_id, credentials):
"""Store OAuth 2.0 credentials in the application's database.

This function stores the provided OAuth 2.0 credentials using the user ID as
key.

Args:
user_id: User's ID.
credentials: OAuth 2.0 credentials to store.
Raises:
NotImplemented: This function has not been implemented.
"""
# TODO: Implement this function to work with your database.
# To retrieve a Json representation of the credentials instance, call the
# credentials.to_json() method.
raise NotImplementedError()

def exchange_code(authorization_code):
"""Exchange an authorization code for OAuth 2.0 credentials.

Args:
authorization_code: Authorization code to exchange for OAuth 2.0
credentials.
Returns:
oauth2client.client.OAuth2Credentials instance.
Raises:
CodeExchangeException: an error occurred.
"""
flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
flow.redirect_uri = REDIRECT_URI
try:
credentials = flow.step2_exchange(authorization_code)
return credentials
except FlowExchangeError, error:
logging.error('An error occurred: %s', error)
raise CodeExchangeException(None)

def get_user_info(credentials):
"""Send a request to the UserInfo API to retrieve the user's information.

Args:
credentials: oauth2client.client.OAuth2Credentials instance to authorize the
request.
Returns:
User information as a dict.
"""
user_info_service = build(
serviceName='oauth2', version='v2',
http=credentials.authorize(httplib2.Http()))
user_info = None
try:
user_info = user_info_service.userinfo().get().execute()
except errors.HttpError, e:
logging.error('An error occurred: %s', e)
if user_info and user_info.get('id'):
return user_info
else:
raise NoUserIdException()

def get_authorization_url(email_address, state):
"""Retrieve the authorization URL.

Args:
email_address: User's e-mail address.
state: State for the authorization URL.
Returns:
Authorization URL to redirect the user to.
"""
flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
flow.params['access_type'] = 'offline'
flow.params['approval_prompt'] = 'force'
flow.params['user_id'] = email_address
flow.params['state'] = state
return flow.step1_get_authorize_url(REDIRECT_URI)

def get_credentials(authorization_code, state):
"""Retrieve credentials using the provided authorization code.

This function exchanges the authorization code for an access token and queries
the UserInfo API to retrieve the user's e-mail address.
If a refresh token has been retrieved along with an access token, it is stored
in the application database using the user's e-mail address as key.
If no refresh token has been retrieved, the function checks in the application
database for one and returns it if found or raises a NoRefreshTokenException
with the authorization URL to redirect the user to.

Args:
authorization_code: Authorization code to use to retrieve an access token.
state: State to set to the authorization URL in case of error.
Returns:
oauth2client.client.OAuth2Credentials instance containing an access and
refresh token.
Raises:
CodeExchangeError: Could not exchange the authorization code.
NoRefreshTokenException: No refresh token could be retrieved from the
available sources.
"""
email_address = ''
try:
credentials = exchange_code(authorization_code)
user_info = get_user_info(credentials)
email_address = user_info.get('email')
user_id = user_info.get('id')
if credentials.refresh_token is not None:
store_credentials(user_id, credentials)
return credentials
else:
credentials = get_stored_credentials(user_id)
if credentials and credentials.refresh_token is not None:
return credentials
except CodeExchangeException, error:
logging.error('An error occurred during code exchange.')
# Drive apps should try to retrieve the user and credentials for the current
# session.
# If none is available, redirect the user to the authorization URL.
error.authorization_url = get_authorization_url(email_address, state)
raise error
except NoUserIdException:
logging.error('No user ID could be retrieved.')
# No refresh token has been retrieved.
authorization_url = get_authorization_url(email_address, state)
raise NoRefreshTokenException(authorization_url)


Related Topics



Leave a reply



Submit