Sending email via GMail in C#/.NET using SmtpClient

Updated on Friday, September 13, 2019

Gmail Logo

Here’s a quick code snippet that configures SmtpClient to send email using Gmail’s SMTP server:

This can be frustratingly difficult to get right so I’ll run through each setting quickly.

DeliveryMethod: Set to SmtpDeliveryMethod.Network, the alternatives are copying the email to a directory for pickup by a different application. We want to connect directly to Gmail.

UseDefaultCredentials: False, as we’ll be providing our own credentials later. Setting properties in the right order is apparently important for SmtpClient, although the Microsoft documentation doesn’t mention this. Make sure you set UseDefaultCredentials to false before setting the Credentials property.

EnableSsl: True. SSL or TLS is required.

Host: smtp.gmail.com for this example. Note that this server restricts you to sending 2,000 emails per day. There is a less restrictive option for G Suite customers (smtp-relay.gmail.com) and a more restrictive server that can only send messages to Gmail or G Suite addresses (aspmx.l.google.com).

Port: Google says to use 465 for SSL and 587 for TLS. I’ve found that 587 with EnableSSL set to true works fine.

Credentials: Your Gmail address and password in a NetworkCredential. If your account has 2 step (multi factor) authentication then this won’t work. You can generate an app password easily and use this instead of your regular password. It’s also possible to use OAuth.

In the comments below Shika Helmy suggests also setting the Timeout property to 20000.

You can now use smtp.Send() to send the email.

Because it’s likely to be your personal account and there is a 2,000 message cap on sending I’d only recommend using this for small scale projects. You don’t want to get your Gmail account blocked. For higher volume I’d look at using SendGrid or similar.

One last note - while I’ve used SmtpClient for all sorts of trivial email needs over the years the latest Microsoft documentation marks it obsolete and warns:

SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead

Hope this expanded article helps. I still come back here periodically to cut and paste rather than mess up the property order again...

Add your comment...

Related Posts

(All Code Posts)

(Published to the Fediverse as: Sending email via GMail in C#/.NET using SmtpClient #code #smtp #email #google How to use the C# SmtpClient to send an email through the Gmail SMTP server (updated for two factor authentication). )

Support SHIELD–a small measure of patent sanity

Updated on Thursday, November 12, 2015

A friend pointed me at the SHIELD (PDF) act today. This bill would make unsuccessful patent trolls pay defendants’ legal bills. It’s not as good as my radical plan to fix patents, but it’s a step in the right direction. If you care, let your congressperson know. Here’s the note I just sent to mine:

Dear Rep. Pelosi,

I'm writing to let you know that I support the SHIELD act Introduced by Rep. Peter DeFazio (D-OR) and co-sponsored by Rep. Jason Chaffetz (R-UT). As an entrepreneur and professional software developer I have personally experienced the job destroying effects of ill founded patent litigation. Any step to reduce this drag on our industry is a welcome step.

Regards,

Rob Ellison
San Francisco 

Add your comment...

Related Posts

(All Politics Posts)

(Published to the Fediverse as: Support SHIELD–a small measure of patent sanity #politics #patents Let your congressperson know that you support SHIELD, a small measure of patent sanity. )

Thank you for choosing HSA Bank!

Updated on Sunday, November 6, 2022

Thank you for choosing HSA Bank!

No, thank you HSA Bank for not giving me a choice and then cheekily pinching $2 on every debit swipe.

Add your comment...

Related Posts

(All Etc Posts)

etc, hsa

Reviews and Links for July 2012

Updated on Friday, February 24, 2017

The Sense of an Ending by Julian Barnes

4/5

A personal anti-adventure, gripping and poignant and pedestrian.

 

The Children of the Sky (Zones of Thought, #3) by Vernor Vinge

0/5

Solid, unexpected third installment. Don't read if you haven't read the first two.

 

Links

'robot revolution would end quickly, because the robots would all break down or get stuck against walls' - http://t.co/X4AFepMI

RT @GeoCollective: Daniel @RavenEllison speaking at National Geographic on the importance of #geography and #guerrillageography http://t ...

Aspam, Aomori, Japan - looks like Blade Runner. http://t.co/UePboKyJ

Cloud Atlas trailer http://t.co/etJealdX (on the plus side, lots of reasons for this to be great, on the minus side... Tom Hanks :( ) #fb

[text: “what the fuck, it worked the first time”,... http://t.co/chCeMv8M

Chow Down (at Chick-fil-A): http://t.co/cOuZViuC via @youtube

4 of 5 stars to The Sense of an Ending by Julian Barnes http://t.co/lV8ZrNHL

I side 90% with Jill Stein... http://t.co/zCNzugqD

Naples, Florida, USA snapshot from Catfood WebCams on Android. http://t.co/HACOmEhr

Testing a webcam share from Android... http://t.co/Ha94fZoW

Photo http://t.co/GnDGvPPZ

Rolling up social APIs: https://t.co/qrXnqX7T #todo @myEN

Thanks for the Cash Mr. Bubble Man: http://t.co/ZonD58yD

With More Original Programming On The Way, Netflix TV Viewing Is On The Rise http://t.co/Q8oCNZUv -- missing the point, lack of content

Hubble discovers new Pluto moon http://t.co/kRB95fLu -- Promote Pluto back to a planet immediately!

Amanda Palmer's awesome stop-motion music video [NSFW]: http://t.co/XfGBC9NY

ITHCWY: Hummingbird http://t.co/CHtA5fV3

Clegg: House of Lords is 'flawed' http://t.co/qp6MuKPO -- yes, do this: http://t.co/QNPyzu8X

ITHCWY: Twitter's API has got too painful for me: I've developed a bunch of stupid, niche and vaguely promising… http://t.co/J6Y0EZ62

IT class warfare — It’s not just IBM http://t.co/bK0Nr2lG

Naming Pets http://t.co/syC0kgWa

BBC News - Brian Cox: bank bailout costlier than UK science 'since Jesus' http://t.co/1RSN5g5Z -- amaaaaazzzziiiinnnnngg

"A conversation with my 12 year old self" (video) http://t.co/zYOEKDnN -- freaky

ITHCWY: Shrubbery: A missed opportunity to demand that violators shall provide... another shrubbery! (At the Old… http://t.co/lBSQaDmI

Probably the Higgs: http://t.co/yspWoQlv

Spring cleaning in summer http://t.co/269vRG1O - Google kills iGoogle. It was naff, but it drove a lot of @CatfoodSoftware business. Sad.

Cisco's cloud vision: Mandatory, monetized, and killed at their discretion http://t.co/OkBkKAsA via @extremetech @CiscoSystems

A better idea for House of Lords reform: http://t.co/WXhNgHF4 Agree? vote for http://t.co/svIg4nuG #lordsreform

ITHCWY: House of Lords - time for Legislative Service?: I've mulled the idea of having an upper chamber randomly… http://t.co/6C5cQjz2

You Might Be A Smanker If… http://t.co/L91rDvqV

Cisco locks customers out of their own routers, only lets them back in if they agree to being spied upon and monetized http://t.co/2QIdw42P

Bouncy, bouncy druids, not available outside the UK: http://t.co/mw7XcKth

Division http://t.co/2tIh8IXM via @RavenEllison

Patent troll http://t.co/AY3FIg8W

Operated by the knights who say NI! http://t.co/TkMndo7c

Add your comment...

Related Posts

(Recent Photos)

Hummingbird

Updated on Saturday, October 1, 2022

Hummingbird

A hummingbird investigates a planter at the Presidio of San Francisco.

Add your comment...

Related Posts

(Recent Photos)

(Published to the Fediverse as: Hummingbird #photo #hummingbird Photo of a hummingbird investigating a planter at the Presidio of San Francisco, California. )

Twitter's API has got too painful for me

Updated on Thursday, November 12, 2015

Twitter's API has got too painful for me

I've developed a bunch of stupid, niche and vaguely promising apps on top of the Twitter API. During that time I've slogged through various painful and rapid shifts like changing IDs, authentication schemes and diktats handed down on which parts of the ecosystem Twitter would like to control. I've had to roll my own OAuth and even re-word a blog post to Twitter Support's satisfaction to get a blocked application unblocked again. It's been a pretty frustrating experience but worth rolling with the punches until the past week.

Twitter suspended Cleat, a tool for posting from the command line. So I emailed to ask why, too much effort for them to explain the rationale at the time they're putting the suspension in place I guess. I got an auto-response asking for information they must have already had and I replied to this. A few days later I still hadn't heard back so I emailed again and the ticket had been automatically closed. 

So far just the standard fuck-off-and-die support that you'd expect from a growing company that no longer wants to talk to it's users. But the auto-reply directed me to https://support.twitter.com/forms/ to file a new ticket. None of the options there relate to developers or a suspended application. I tried filing a ticket under 'deactivated account' which seemed the closest.

That form has a hard-coded 'With love,' valediction. Whoever thought that was cute should go through the process of trying to get help a few times. 

This attempt auto-responded to say that my account was not suspended, and would I like to fuck-off-and-die or got back to the forms center?

So I tried another form that actually seemed to submit but haven't heard anything back.

I'd be happy to update my software if I know which vague shifting facet of the Twitter terms of use I'd fallen foul of. Or at least I would have been. I'm just so sick of it that I've pulled Cleat and I'm done with any more personal projects that use the Twitter API. 

Add your comment...

Related Posts

(All Code Posts)

(Published to the Fediverse as: Twitter's API has got too painful for me #code #twitter #cleat #commandline #api Twitter's opaque API policies have led to me no longer developing on the platform. )

Shrubbery

Updated on Wednesday, May 19, 2021

Shrubbery

A missed opportunity to demand that violators shall provide... another shrubbery!

(At the Old Faithful Geyser.)

Add your comment...

Related Posts

(Recent Photos)

(Published to the Fediverse as: Shrubbery #photo #shrubbery Tragically at the Old Faithful Geyser in Calistoga, California they missed the opportunity for a great Monty Python joke. )

House of Lords - time for Legislative Service?

Updated on Thursday, November 12, 2015

House of Lords - time for Legislative Service?

I've mulled the idea of having an upper chamber randomly selected from the public like jury service for some time, often over a pint with a friend who prefers to remain nameless. This friend wrote an outstanding letter to Mark Harper which is included below by his kind permission. 

Mark Harper didn't manage more than a stock response, and neither did Matthew Offord and so it doesn't seem that the British Government is taking up the concept any time soon. We talked about the e-petition system but it turns out that it's limited to 1,000 characters and submissions are vetted for duplicates. There is an existing e-petition with this idea written by Simon Ferrigno which I've voted for, and if you support the legislative service idea please do the same.

Dear Mr Harper

We understand that you are working with the Deputy Prime Minister on the matter of an elected second chamber. We’re sure that many proposals and reports have crossed your desk on this topic. We’d like to share something we came up with when the issue was initially raised a few years ago. Having kept abreast of developments via media reports, we were both surprised not to hear anything similar mooted.

Our suggestion is that the second chamber be made up of ordinary members of the public drawn from across the country, randomly selected from the electoral roll, typically for up to 2 weeks of service. The system would be administered in a similar way to jury duty, albeit on a national basis. These people would be brought together, put up in decent accommodation, well fed, and otherwise made to feel as if their presence and contribution is both valued and important. They will be tutored, in an unbiased fashion, on the background of the Bill under their consideration. The syllabus could be defined by the civil servants who draw up the legislation under consideration. At this point, a multiple choice test on what they have been taught will be administered, but the results will not be revealed.

After the test, they will have the specifics of the Bill explained to them by two barristers (selected by parties for and against). The barristers will have the ability to bring in subject matter experts (perhaps drawing on the talent pool currently in place in the HOL). At the end of the evidentiary stage, the “constitutional jury” will have the opportunity to debate the issues and pose any further questions they may have to the barristers or witnesses.

Once completed, the constitutional jury will vote on the matter(s) at hand. The only votes that will actually count are those cast by people who passed the multiple choice test (as long as a quorum is reached). The results will only be reported as percentages. No one will ever be told if their vote counted, and all members of the constitutional jury are recorded as having served in deciding the matter.

Among the numerous advantages, as we see them, are:

  1. Politicians are often heard bemoaning the lack of public engagement with politics. This is an ideal way of re-engaging ordinary members of the public with the business of politics and what happens in Parliament.
  2. The primacy of the House of Commons will be ensured due to the transience of the members of the second chamber.
  3. There are no expensive elections to be paid for, nor will anyone’s voting record need to be skewed to ensure their re-election.
  4. As this chamber will be entirely made up of randomly selected members of the public, there can be no claims of cronyism.
  5. Voting along party political lines may be reduced; hence the decisions made are those that a random cross section of society deem to be right, rather than the whips.
  6. As the names of the constitutional jury are not disclosed until after the final voting, lobbying by vested interests will be reduced.
  7. The second chamber does not necessarily need to be based in London. In fact, there is no reason why it cannot become a travelling roadshow, convening on a rotating basis in major towns and cities around the UK. This may go some way towards quietening some of the accusations that Parliament is London-centric and lessening talk about the Westminster Village.
  8. Should Parliamentary time be short and the workload high, multiple constitutional juries can be assembled (perhaps in different locations), to work in parallel considering different Bills.

We realise that some members of the House of Lords serve on multiple select committees. We’ll admit to not having a plan for how these will be staffed in the future. One could assume that for now, they can be appointed by Parliament continuing to draw on the talent pool from the current HOL and augmenting any vacancies with new appointments proposed by a committee of civil servants.

We realise that all parties are currently wedded to the idea of an elected second chamber. Is there any way that this could work as a viable alternative?

Yours sincerely...

Photo credit: UK Parliament cc

Add your comment...

Related Posts

(All Politics Posts)

(Published to the Fediverse as: House of Lords - time for Legislative Service? #politics #politicalreform #legislativeservice #democracy Legislative Service is the right answer to reforming the House of Lords. )

Reviews and Links for June 2012

Updated on Friday, February 24, 2017

The Marriage Plot by Jeffrey Eugenides

3/5

A love triangle set in the turmoil of post-graduation. Well written but left me a little cold, I just didn't care for the characters or the sudden resolution.

 

Links

An important update from the International Earth Rotation Service http://t.co/n5VcLNH3 <- warning,="">

Seeing Beyond the Human Eye: Video of beautiful scientific and artistic photography http://t.co/aZsFEfh1

ITHCWY: Mission:Explore Food - Get It Now: I posted a few months ago about my brother's crowd funded book, Mission… http://t.co/1A2FEkHN

Kate's #MEF151 looks hard! http://t.co/Qo4N4weY #fb

Pyura Chilensis, the living rock http://t.co/54moGgML

Ghosts With Shit Jobs: http://t.co/CjDH5mz6 #fb

Google's Nexus 7 tablet image leaks onto the Web http://t.co/nuLji4zz via @CNET - holy crap that's a big bezel #io12

Robot Hand beats you at Rock-Paper-Scissors every time. http://t.co/W4K1zAeq (Robot hand crushes rock, robot hand crushes scissors...)

Moon Landing http://t.co/oHFSCowO

Patent 'trolls cost $29bn a year' http://t.co/VQRiKFtb

Facebook Just Changed Your Email Without Asking http://t.co/z9QRi3qP

#Bernal now has a Solar Pump http://t.co/e40lcNLY

House of Lords reform: Nick Clegg's crazy plan is a pay day for has-beens and never-wozzers via @Telegraph http://t.co/kDjbqTFh

Future of ATA = more dishes. Not that expensive. What about it @NancyPelosi ? #SETIcon http://t.co/uobbZ065

Meeting moons at #SETIcon http://t.co/MXykt1QK

RT @erinbiba: http://t.co/Ahh0IhXq - a directory of ways for YOU to participate in space exploration. (Build a rover, get your name on a ...

Is Jupiter helpful to life on Earth? In some ways yes, in some ways no. #SETIcon http://t.co/pG1U3mf3

http://t.co/mZWx5FIr Turing Suicide in doubt?

Gaia corollary: http://t.co/9lPllPbT #SETIcon (re global organism)

Intelligent life: it's all about the unknown unknowns #SETIcon http://t.co/Goo7ngUq

Gorgeous start to the second full day of #SETIcon 2. http://t.co/f0bbwW4V

Was God required for the Big Bang panel rather unfairly stacked 100% against God #SETIcon http://t.co/Keg164Vo

How to find aliens: advice from NASA, SETI and the EMH. #SETIcon http://t.co/HAHZrbv6

ITHCWY: SETIcon 2: I'm at SETIcon 2 this weekend. It's a mix of science, sci-fi, religion and general speculation… http://t.co/jifR8Ang

http://t.co/FZo6GzxJ #todo #SETIcon @myEN Kepler archives opening in October

Success of Kepler Mission is staggering. Discovering water worlds, planets everywhere. #SETIcon http://t.co/4EytfDks

On the cusp of routine spaceflight - at #SETIcon http://t.co/iUU6GgEz

I'm reading Mission:Explore Food on @graphicly! http://t.co/z0iqfQKJ

Far-Fetched Scams Separate the Gullible from Everyone Else http://t.co/M8SyoAvH

Scout: get notified every time Congress proposes legislation with keywords you care about http://t.co/OlU04P45

Exoplanets http://t.co/CAu4C9v9 #fb

Falsehoods programmers believe about time - riff on the malleability of computer time http://t.co/sznLoFlH

JustAnswer Becomes http://t.co/U0xZtr5Z, Raises $25 Million Series A http://t.co/r5IQzmFZ via @techcrunch #PearldotcomLaunch

VatorNews - JustAnswer rebrands as Pearl, raises $25M http://t.co/MTveL1qB via @po_st #PearldotcomLaunch

http://t.co/U0xZtr5Z Has Professional Advice, for a Price http://t.co/RnyqID2G via @mashable #PearldotcomLaunch

Andy Kurtzig Raises $25M To Take Expert Services Online With http://t.co/U0xZtr5Z - http://t.co/PPFhu3q8 #PearldotcomLaunch

JustAnswer Becomes Pearl, Comes Out From Under the Radar http://t.co/5l3UTZ1M #PearldotcomLaunch

A Pearl (.com) Comes Out of http://t.co/LZa65dD3 http://t.co/tUhBuEhe via @HuffPostTech #PearldotcomLaunch

Customer Story - Dr. David Helps Nick Recover from Brain Hemorrhage: http://t.co/HK59IUw2 via @pearl.com #PearldotcomLaunch

RT @Pearldotcom: http://t.co/x1sGSaBc is now in beta, come check us out at http://t.co/ePbqZPiU! #PearldotcomLaunch

RT @MissionExplore: Mission:Explore Food – Video yourself doing one of the missions from the book and get a free copy http://t.co/TpkoBOaY

ITHCWY: Near-plurality of idiocy: "In the 30 years since Gallup started asking people whether they believe humans… http://t.co/9f5FoX9Z

BBC News - Alan Turing: why the tech world's hero should be a household name http://t.co/5eqmNyXY

ITHCWY: Petrol & Marks & Spencer: I recently got back from a trip back to the UK. Every time I go back these days… http://t.co/cV0N8tY7

+1 Error Code 451: an HTTP error for censorship http://t.co/OoA942o8

#todo @myEN Mobile-Friendly Pet Locator PetHub Closes $1.3 Million Seed Round http://t.co/DtkMMSoj

Bridge birthday thing... http://t.co/bBEc7TiC

Brrrr-earnal http://t.co/dD4FiXrv

Defensive Patent License: judo for patent-trolls http://t.co/h6Eq82kr

3 of 5 stars to The Marriage Plot by Jeffrey Eugenides http://t.co/aJwE7cIz

Check out this presentation : How to stop sucking and be awesome instead http://t.co/fqW1ZTG5 via @slideshare

Transit of Venus AND Sutro Tower Serendipitously Photographed from Bernal Hill http://t.co/bZAogCf8

Office has laid on EURO 2012 coverage. http://t.co/8dDStstW

Ridiculously nice walk with Rudy. http://t.co/u6E9H1Gg

ITHCWY: Playmobil http://t.co/bIuMirqh

Add your comment...

Related Posts

(All Politics Posts)

Mission:Explore Food - Get It Now

Updated on Friday, February 24, 2017

I posted a few months ago about my brother's crowd funded book, Mission:Explore Food. The funding was successful, and the ebook version is available now.

Add your comment...

Related Posts

(All Reviews)

(Published to the Fediverse as: Mission:Explore Food - Get It Now #reviews #missionexplore #food Mission:Explore Food - Get It Now )