MailKit authentication fails - asp.net-core

I have the code below
MimeMessage message = new MimeMessage();
MailboxAddress from = new MailboxAddress("Admin",
"myemail#gmail.com");
message.From.Add(from);
MailboxAddress to = new MailboxAddress("User",
"myemail2#gmail.com");
message.To.Add(to);
message.Subject = "Hi user";
BodyBuilder bodyBuilder = new BodyBuilder();
bodyBuilder.TextBody = "message body here";
message.Body = bodyBuilder.ToMessageBody();
SmtpClient client = new SmtpClient();
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Connect("smtp.gmail.com", 465, true);
client.Authenticate("myemail#gmail.com", "pass");
client.Send(message);
client.Disconnect(true);
client.Dispose();
It says my credentials are not correct even though they are. I'm using MailKit and MimeMessage.
What am I doing wrong here?

try to use port 587 instead of 465.
Here's the link to my github repository, a simple project to send mails.
https://github.com/osman-developer/sendingMails

You can use something like that.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Test Project",
"your email"));
message.To.Add(new MailboxAddress("pritom", email));
message.Subject = "Hi,this is demo email";
message.Body = new TextPart("plain")
{
Text = "Hello,My First Demo Mail it is.Thanks",
};
//add attach
MemoryStream memoryStream = new MemoryStream();
BodyBuilder bb = new BodyBuilder();
using (var wc = new WebClient())
{
//bb.Attachments.Add("attachmentName",
wc.DownloadData("wwwroot/Images/H.pdf"));
bb.Attachments.Add("Email.pdf",
wc.DownloadData("wwwroot/Images/Email.pdf"));
//bb.Attachments.Add("H.pdf", new MemoryStream());
}
message.Body = bb.ToMessageBody();
//end attach
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("your email",
"yourpassword");
client.Send(message);
client.Disconnect(true);
}
Update
go to this link
enter link description here
and allow a less secure app.

If you are facing the same issue, go on your gmail account > security > allow less secure apps. This solved my problem

Related

asp.net send email with excel attachement

I want to create excel file and send it as attachment via email
hear is my code for creating excel file but i can't send it by email , the email sent but without attachment.
this for creating excel file.
DataTable dt = new DataTable("Grid");
dt.Columns.AddRange(new DataColumn[4] { new DataColumn("H_Id"),
new DataColumn("H_Name"),
new DataColumn("H_PassNo"),
new DataColumn("H_Pass_Issue"),
});
var marydatas = from MarryData in this._context.MarryData.Take(10)
select MarryData;
foreach (var marryData in marydatas)
{
dt.Rows.Add(marryData.H_Id, marryData.H_Name, marryData.H_PassNo, marryData.H_Pass_Issue);}
byte[] bytes = null;
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
bytes = stream.ToArray();
}
}
and this for sending email
var message = new MimeMessage();
message.From.Add(new MailboxAddress("test project", "maazonuae#gmail.com"));
message.To.Add(new MailboxAddress("naren", "a.saaeed81#gmail.com"));
message.Subject = "test maazon";
message.Body = new TextPart("HTML Table Exported Excel Attachment")
{
Text = "hello"
};
var builder = new BodyBuilder();
builder.Attachments.Add("Customers.xlsx", new MemoryStream(bytes));
var body = builder.ToMessageBody();
var emailBody = new MimeKit.BodyBuilder
{
};
emailBody.Attachments.Add("Customers.xlsx", bytes);
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("maazonuae#gmail.com", "maazonuae2021");
client.Send(message);
client.Disconnect(true);
}
so when it run just send email without attachment and send (Text = "hello") in attached file not in body message.
thanks
i found solution
var message = new MimeMessage();
message.From.Add(new MailboxAddress(Joey", "joey#friends.com));
message.To.Add(new MailboxAddress("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
var builder = new BodyBuilder();
// Set the plain-text version of the message text
builder.TextBody = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday. I was hoping you could make it.
Will you be my +1?
-- Joey
";
builder.Attachments.Add("myFile.xlsx", bytes);
// Now we just need to set the message body and we're done
message.Body = builder.ToMessageBody();
////////////////////////////////////////////////////////////
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("maazonuae#gmail.com", "maazonuae2021");
client.Send(message);
client.Disconnect(true);
}

How to send email to current logged in user

I am storing the email of the user in session
var v = //login query
Session["LoggedUserEmail"] = v.email.ToString();
Then after login I want to send an email to the current logged in user and for that purpose I am passing Session["LoggedUserEmail"] in Msg.To.Add but its not working.
This is what I am doing
public void Execute(IJobExecutionContext context)
{
System.Net.Mail.MailMessage Msg = new System.Net.Mail.MailMessage();
Msg.From = new MailAddress("abc#gmail.com");
Msg.To.Add(Session["LoggedUserEmail"].ToString());
Msg.Subject = "Email";
Msg.Body = "Hi";
Msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("abc#gmail.com", "xxxxxxx");
smtp.EnableSsl = true;
smtp.Send(Msg);
Response.Write("Email Sent");
}
Am I doing something wrong? if yes, then is there any other way to get the job done?
I am using quartz.net and implemented IJob interface in my mvc controller.
The job executes on a different thread than the one that schedules it. You must pass in any data you need by using the JobDataMap when creating/scheduling the job.

sending email from Controller mvc4

I am trying to send send email through below action method
[HttpPost]
public ActionResult ForgotPassword1()
{
dbAlKhaleejEntities _context = new dbAlKhaleejEntities();
var email = Request["Email"];
var email_adress = _context.CUSTOMERs.First(em => email == em.CUSTOMER_EMAIL);
var mailto = email_adress.CUSTOMER_EMAIL;
MailMessage msg = new MailMessage();
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Credentials = new NetworkCredential("umairliaquat63#gmail.com", "abc");
client.Host = "smtp.gmail.com";
client.Port = 587;
msg.From = new MailAddress("umairliaquat63#gmail.com");
msg.To.Add(mailto);
msg.Subject = "Password recovery";
msg.Body = "Test Recovering the password";
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Send(msg);
return RedirectToAction("forgetPassword");
}
but at line "client.Send(msg)" , it is throwing exception "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required". How I should solve this problem
As far as I know you don't need write your own code cause SmtpClient can use your configuration:
<system.net>
<mailSettings>
<smtp from="It's me <its#my.email>">
<network host="smtp.ip.or.domain" port="527" defaultCredentials="false" userName="noreply" password="12345" enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
Verify your mail settings twice. In addition, the SMTP server can reject connections for IP's from a black list, or not from a white list. The SMTP server can detect your mail as a spam.
You can use your own local SMTP or specialized servises to mass mailings.
Try this snippet :
using (var client = new SmtpClient(SmtpServerHost, SmtpPort)
{
Credentials = new NetworkCredential(NetworkCredentialUserName, Password),
EnableSsl = this.enableSSL
}
)
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress(FromMailingAddress);
msg.Subject = this.Subject;
}

Asp.Net Mvc Receive Mail Issue

I have one problem about receive email. Now, I write Contact page in my project. If some user wanna send email, he/she write email adress and message and click Send buttom. My code send from berdankoca#gmail.com to berdankoca#gmail.com. I couldn't understand why it didn't sent from email area to berdankoca#gmail.com
My Code
[HttpPost]
public ActionResult About(string name, string email, string message)
{
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(email);
mailMessage.To.Add(new MailAddress("berdankoca#gmail.com"));
mailMessage.Subject = "Deneme";
mailMessage.SubjectEncoding = System.Text.Encoding.Default;
mailMessage.Body = message;
mailMessage.BodyEncoding = System.Text.Encoding.Default;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Credentials = new System.Net.NetworkCredential("berdankoca#gmail.com", "xxxx");
client.EnableSsl = true;
client.Send(mailMessage);
return View();
}
I hope I can explain. Thanks for all replies.

HttpClient throws error on SendAsync (C#)

My code (C#):
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.PreAuthenticate = true;
//httpClientHandler.UseDefaultCredentials = true;
httpClientHandler.Credentials = CredentialCache.DefaultNetworkCredentials;
//httpClientHandler.Credentials = new NetworkCredential("usr", "pw", "domain");
httpClientHandler.CookieContainer = new CookieContainer();
var httpcontent = new StringContent(content);
HttpClient httpClient = new HttpClient(httpClientHandler);
httpClient.DefaultRequestHeaders.ExpectContinue = false;
httpClient.BaseAddress = ews_url;
// var request = httpClient.PostAsync(ews_url, httpcontent);
var requestMessage = new HttpRequestMessage();
requestMessage.RequestUri = ews_url;
requestMessage.Content = httpcontent;
requestMessage.Method = HttpMethod.Post;
var request = httpClient.SendAsync(requestMessage);
HttpResponseMessage response = await request; // --> Error
the instance of HttpClient (httpClient) always runs into an exception in the line marked with the --> Error comment. I can not find any wrong code lines. The exception says: "the underlying connection closed", "Error on sending" but the connection is not closed as you see. I tried several options like "UseDefaultCredentials true/false", "new NetworkCredentials".
My scenario is an App sending soap messages to exchange web services (ews).
Do you have any ideas solving my problem?