C# SMTP Console App using free google smtp - c#

I found the below snippet of code to send email.
It doesn't work for me.
It times out on send.
Any ideas, anyone?
It opens a blank window, then sits there and does nothing.
I get no mail.
Eventually it times out.
Sorry for being verbose. Stackexchange has weird filters that won't allow me to post question unless I added more text to the body. It complained there was too much code and not enough text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace TestHello
{
class Program
{
static void Main(string[] args)
{
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.Credentials = new NetworkCredential("klloil#gmail.com", "xxxxxxx");
smtpClient.EnableSsl = true;
MailMessage message = new MailMessage();
message.To.Add("kal#gmail.com");
message.Subject = "Password Manager Sync Account Created";
message.From = new MailAddress("xxxx#gmail.com");
message.Body = "My Email message";
smtpClient.Send(message);
}
}
}

Related

Why do I get 'Message rejected: Email address is not verified' when trying to send an SES email?

I am trying to send an email from email1 to email2. But I am getting the following error:
Transaction failed. The server response was: Message rejected: Email address is not verified. The following identities failed the check in region CA-CENTRAL-1: alex.smail#yahoo.ca, Sender Name email1#yahoo.ca, email2#yahoo.com
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
namespace ConsoleApp3
{
internal class Program
{
static void Main(string[] args)
{
Email("DO TEST");
}
public static void Email(string htmlString)
{
String FROM = "email1#yahoo.ca";
String FROMNAME = "Sender Name";
String TO = "email2#yahoo.com";
String SMTP_USERNAME = "kiffretM5C2PFESI5W";
String SMTP_PASSWORD = "BLeMDSkjioourdvhvbhvhTMHAVfuG6mcAXibbTmQpe7WX";
String HOST = "email-smtp.ca-central-1.amazonaws.com";
int PORT = 587;
String SUBJECT =
"Amazon SES test (SMTP interface accessed using C#)";
// The body of the email
String BODY =
"<h1>Amazon SES Test</h1>" +
"<p>This email was sent through the " +
"<a href='https://aws.amazon.com/ses'>Amazon SES</a> SMTP interface " +
"using the .NET System.Net.Mail library.</p>";
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress(FROM, FROMNAME);
message.To.Add(new MailAddress(TO));
message.Subject = SUBJECT;
message.Body = BODY;
using (var client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
client.Credentials =
new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
client.EnableSsl = true;
try
{
Console.WriteLine("Attempting to send email...");
client.Send(message);
Console.WriteLine("Email sent!");
}
catch (Exception ex)
{
Console.WriteLine("The email was not sent.");
Console.WriteLine("Error message: " + ex.Message);
}
}
}
}
}
It would appear that you are using Amazon SES in sandbox mode.
From Moving out of the Amazon SES sandbox - Amazon Simple Email Service:
To help prevent fraud and abuse, and to help protect your reputation as a sender, we apply certain restrictions to new Amazon SES accounts.
We place all new accounts in the Amazon SES sandbox. While your account is in the sandbox, you can use all of the features of Amazon SES. However, when your account is in the sandbox, we apply the following restrictions to your account:
You can only send mail to verified email addresses and domains, or to the Amazon SES mailbox simulator.
You can send a maximum of 200 messages per 24-hour period.
You can send a maximum of 1 message per second.
While operating in sandbox mode, you will need to verify every email address before it can receive email.

How to fix GMail SMTP error: "The SMTP server requires a secure connection or the client was not authenticated."

Below is the code I'm using. Please advise on how this can be rectified.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Net.Mail;
public partial class mailtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendEmail(object sender, EventArgs e)
{
lblmsg.Text = "";
try
{
using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
{
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
//if (fuAttachment.HasFile)
//{
// string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
// mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
//}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = txtsmtphost.Text.Trim();
smtp.EnableSsl = false;
if (chkssl.Checked == true)
{
smtp.EnableSsl = true;
}
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(txtport.Text);
smtp.Send(mm);
lblmsg.ForeColor = System.Drawing.Color.DarkGreen;
lblmsg.Text = "Email sent successfuly !!";
//ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent successfuly !!');", true);
}
}
catch (Exception ex)
{
lblmsg.ForeColor = System.Drawing.Color.Red;
lblmsg.Text = "Failed " + ex.ToString();
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Failed');", true);
}
}}
The error message is:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. Learn more at at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)
Since this question keeps coming up as the first on Google, what today worked for me (11 June 2022) is what I will share. This question has been asked many times in similar way and many different things have worked for many people, but that stops now, there are no work around in "code" anymore (assuming your code is perfect but throwing exception as written in the title above)! Why because Google made a change (from https://support.google.com/accounts/answer/6010255):
Less secure apps & your Google Account:
To help keep your account secure, from May 30, 2022, ​​Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.
Important: This deadline does not apply to Google Workspace or Google Cloud Identity customers. The enforcement date for these customers will be announced on the Workspace blog at a later date.
Now what do you do, its simpler then you think, go to https://myaccount.google.com/, Click "Security", enable Two-step Verification, once done, come back to the myaccount Security page, you will see "App passwords", open that, it will give you options for what you are trying to make a password for (a bunch of devices), select "Windows Computer", make a password, copy it, use this password in the NetworkCredential class object in your code, and your emails should start working again through Code.
This wasted so much of my hours yesterday, my Winforms app was working perfect till a couple days back it stopped sending emails.
The SMTP server requires a secure connection or the client was not authenticated.
To fix this error Go to your google account and generate an apps password
When running your code use the password generated instead of the actual users password.
This happens most often when the account has 2fa enabled.
Example with SmtpClient
using System;
using System.Net;
using System.Net.Mail;
namespace GmailSmtpConsoleApp
{
class Program
{
private const string To = "test#test.com";
private const string From = "test#test.com";
private const string GoogleAppPassword = "XXXXXXXX";
private const string Subject = "Test email";
private const string Body = "<h1>Hello</h1>";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential(From , GoogleAppPassword),
EnableSsl = true,
};
var mailMessage = new MailMessage
{
From = new MailAddress(From),
Subject = Subject,
Body = Body,
IsBodyHtml = true,
};
mailMessage.To.Add(To);
smtpClient.Send(mailMessage);
}
}
}
You should enable the less secure app settings on the Gmail account you are using to send emails. You can use this Link to enable the settings.
More information about your problem here.

how to send email using smtp in c#?

I have a list of data from a database and I have Email Id's in database, i have to send email to those ID's where if its retention date is tomorrow means i have to send an intimation email as reminder by today,i want to send email, and i will use service to send it daily, but my email part is not working..below is my code..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace SendingEmail
{
public class SendingMail
{
public static void SendMail(string recipient, string subject, string
body, string attachmentFilename)
{
//method to send email
MailMessage mail = new MailMessage();
try
{
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587);
SmtpServer.EnableSsl = true;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "my password");
string From = "my email#gmail.com";
string To = "email.com";
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
MailMessage msg = new MailMessage(From, To);
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment
(#"C:\Users\rahul.chakrabarty\Desktop\logg.txt");
mail.Attachments.Add(attachment);
SmtpServer.Send(mail);
}
//To cathch Exception
catch (Exception ex)
{
Console.WriteLine("unable to send" + ex);
}
}
}
}
My error is "unable to sendsystem.InvalidOperationException: A from address must be specified"..This is my error
You said
String from = "my email#gmail...
But nowhere have you actually assigned this string to the mail.From property - you've gone and made a new MailMessage using that from address, and called it msg:
MailMessage msg = new MailMessage(From, To)
but you aren't sending the msg mail, you're sending the mail mail:
SmtpServer.Send(mail);
The same problem exists with the To address on the mail variable
Basically, the code is all messed up: you make TWO MailMessage objects, set half the necessary things on one, the other half of necessary things on the other, and then try to send one of them with incomplete details. It's kinda like you copied and pasted two different tutorials together but didn't get enough of either of them to get a complete MailMessage ready for sending
I could have fixed this all up for you and posted working code, but I haven't for two reasons: 1) it's very easy to do these small changes yourself, and 2) I want YOU to do it as a learning exercise rather than just giving you the answer :)
Make sure you don't put a space in the email address either

Unable to read data from the transport connection?

This is my first post on Stack, and I've literally just started programming, so please, be patient.
I'm attempting to send an email to "x" email address when Button 1 is pressed. I've looked around, and every thread is jargon-heavy and not in my context. Please pardon me if this is a "newb' question, or if it's already thouroughly answered somewhere else.
The error I'm getting is "
Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed."
Here's my code
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 465;
smtp.Credentials = new NetworkCredential("myemail", "mypassword");
string to = "toemail";
string from = "myemail";
MailMessage mail = new MailMessage(from, to);
mail.Subject = "test test 123";
mail.Body = "test test 123";
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
Any help is greatly appreciated!
The error you're getting could come from a plethora of things from a failed connection, to the server rejecting your attempts, to the port being blocked.
I am by no means an expert on SMTP and its workings, however, it would appear you are missing setting some of the properties of the SmtpClient.
I also found that using port 465 is a bit antiquated, and when I ran the code using port 587, it executed without an issue. Try changing your code to something similar to this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
namespace EmailTest
{
class Program
{
static void Main(string[] args)
{
SendMail();
}
public static void SendMail()
{
MailAddress ma_from = new MailAddress("senderEmail#email", "Name");
MailAddress ma_to = new MailAddress("targetEmail#email", "Name");
string s_password = "accountPassword";
string s_subject = "Test";
string s_body = "This is a Test";
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
//change the port to prt 587. This seems to be the standard for Google smtp transmissions.
Port = 587,
//enable SSL to be true, otherwise it will get kicked back by the Google server.
EnableSsl = true,
//The following properties need set as well
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ma_from.Address, s_password)
};
using (MailMessage mail = new MailMessage(ma_from, ma_to)
{
Subject = s_subject,
Body = s_body
})
try
{
Console.WriteLine("Sending Mail");
smtp.Send(mail);
Console.WriteLine("Mail Sent");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
Console.ReadLine();
}
}
}
}
Tested to work as well. Also of note: if your Gmail account does not allow "Less Secure" apps to access it, you'll get an error and message sent to your inbox stating an unauthorized access attempt was caught.
To change those settings, go here.
Hope this helps, let me know how it works out.

Send mail to multiple receipts from Database using Web service in asp .net c#

I have a sql server table in which im inserting Mail ID, subject,And Body of the mail.
And also i displayed the mail details in a gridview in another page. And there is checkbox for each row. Here I want to send these mails to corresponding Email IDs when user checked corresponding checkbox. The actuall problem is that i want to create a web service to send mail. Please help me to create a web service. I tried in some ways. My last Code for to create web service is given below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Mail;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MailService : System.Web.Services.WebService
{
public MailService()
{
//InitializeComponent();
}
[WebMethod]
public bool SendMail(string toAddress, string subject, string body)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("proc_MailData", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds);
try
{
MailMessage msg = new MailMessage();
msg.From = "john#averla.in";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string subjct = ds.Tables[0].Rows[i]["MSubject"].ToString();
string mail = ds.Tables[0].Rows[i]["MailID"].ToString();
string bdy = ds.Tables[0].Rows[i]["Body"].ToString();
msg.To = mail;
msg.Body = bdy;
msg.Subject = subjct;
}
SmtpMail.SmtpServer = "maildemo.averla.in";
SmtpMail.Send(msg);
return true;
}
catch (Exception exp)
{
return false;
}
}
}
1- add using statement
using System.Net.Mail;
2- to execute the smtp client
SmtpClient client = new SmtpClient();
client.Credentials=new NetworkCredential(username,password);
client.Send(message);
3- after you compile your web service and publish it, you should be able to navigate to the url and it will show you the operations like the image
then in your application, you can add the reference like i stated in the comments before
here some links that might help you
SmtpClient class
How to: Add a Reference to a Web Service
hope it will help you
regards

Categories