Send Email via C# Through Google Apps Account

Send Email via C# through Google Apps account

There is no need to hardcode all SMTP settings in your code. Put them in web.config instead. This way you can encrypt these settings if needed and change them on the fly without recompiling your application.

<configuration>
<system.net>
<mailSettings>
<smtp from="example@domain.example" deliveryMethod="Network">
<network host="smtp.gmail.com" port="587"
userName="example@domain.example" password="password"/>
</smtp>
</mailSettings>
</system.net>
</configuration>

End when you send email just enable SSL on your SmtpClient:

var message = new MailMessage("navin@php.net");
// here is an important part:
message.From = new MailAddress("example@domain.example", "Mailer");
// it's superfluous part here since from address is defined in .config file
// in my example. But since you don't use .config file, you will need it.

var client = new SmtpClient();
client.EnableSsl = true;
client.Send(message);

Make sure that you're sending email from the same email address with which you're trying to authenticate at Gmail.

Note: Starting with .NET 4.0 you can insert enableSsl="true" into web.config as opposed to setting it in code.

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);
}

Sending email in .NET through Gmail

Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}

Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting.

  • If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password.
  • If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.

I have a Google Service Account, how do I use C# on server side to send an email?

gmail api option.

In order to use service accounts with your workspace domain you need to set up the service account and enable domain wide deligation

Google has sevral very good guidles on how to set it up. The best IMO beingPerform Google Workspace Domain-Wide Delegation of Authority

You will just need to rember to set the scope https://www.googleapis.com/auth/gmail, instead of https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.group shown in the example

After that its simply a matter of using the standard service account code and adding the user that you wish to deligate as

var credential = GoogleCredential.FromFile(serviceAccountCredentialFilePath)
.CreateScoped(scopes);
var gsuiteUser = "noreply@yourdomain.com";

var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});

This is a previous question related to this. How to use gmail api with service accounts or google Oauth in C# for sending mails? However im not sure if you are looking for a smtp answer or a Gmail api answer.

smtp / imap option.

If you want to go though the SMTP / IMAP you need to check Xoauth2. The procedure is the same you will need to set up domain wide delegation to your domain account but the scope changes you need to use https://www.googleapis.com/auth/gmail.imap_admin

I am not aware of any .net examples of this.

How to send email via SMTP from my corporate gmail address using C#

I just tested with your code on my company G-Suite account.

After allowing users to manage their own settings, you need to make sure that the username provided in the NetworkCredential object has been configured to "Allow less secure apps". You can get to it by:

  1. Enable users to manage their own settings (you've already done this)
  2. Going to (in this case) to the Google Account Page for info@mydomain.com.
  3. Clicking "Sign In and Security"
  4. Scroll to the bottom and make sure the slider is on.

The first step may take some time to propagate to all users in G-Suite.

Note: You will also get this error if the password or username are incorrect.

If you've done all of the above and it still doesn't work, you may need to configure SPF in your DNS settings. See Authorize email senders with SPF.

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

C# Unable to send email from G Suite Company account

The port 465 is the issue. The SmtpClient EnableSsl option is actually using TLS. Gmail's TLS port is 587.

From Microsoft's Documentation:

https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.enablessl?view=netframework-4.8

The SmtpClient class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information.

An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported.

Sending an email from Gmail Alias in a Google Workspace

The code was fine

Despite having set up the alias in admin.google.com, I had to log into Gmail, click the cog, then more settings.

From here, click the accounts tab, and under the Send mail as, click on Add another email address, creating another alias. Not sure why I have options to do this in 2 places



Related Topics



Leave a reply



Submit