SendAsync Smtp Mail Error - c#

Application requires that a use SendAsync rather than just Send. So i Made a Class CEmailServer and set up everything. So far Send works fine but when changing it to work with SendAsync it does not. I Created a Method to be called when a mail is sent and the userToken is in place but it keeps failing. i Can't find my error. Here is my code :
static bool mailSent = false;
//Method for Sending with attachment.
public void SendEmail(string Address, string Recipient, string Subject, string Body, string Dir)
{
var fromAddress = new MailAddress("someadress.kimberley#gmail.com", "My Company");
var toAddress = new MailAddress(Address, Recipient);
const string fromPassword = "password";
string subject = Subject;
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.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userState = "Test";
message.Attachments.Add(new Attachment(Dir));
smtp.SendAsync(message,userState);
message.Dispose();
}
}
//Method for Sending regular message without attachment.
public void SendEmail(string Address, string Recipient, string Subject, string Body)
{
var fromAddress = new MailAddress("someadress.kimberley#gmail.com", "My Company");
var toAddress = new MailAddress(Address, Recipient);
const string fromPassword = "password";
string subject = Subject;
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.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userState = "Message Sent";
smtp.SendAsync(message, userState);
message.Dispose();
}
}
//Method to be called when sending is complete
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Cancelled)
{
MessageBox.Show("Sending Canc");
}
if (e.Error != null)
{
MessageBox.Show("Error Sending Mail");
}
else
{
MessageBox.Show("Message sent.");
}
mailSent = true;
}
Thank you very much!

You are disposing the message before the send can complete. You should be disposing them in the SendCompleted callback event. Here's an example of the best way to dispose the client and the message.
Your code should look something like this:
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
};
smtp.SendCompleted += (s, e) => {
SendCompletedCallback(s, e);
smtp.Dispose();
message.Dispose();
};
string userState = "Test";
message.Attachments.Add(new Attachment(Dir));
smtp.SendAsync(message, userState);

Related

having trouble sending mail in asp.net core 5 App

I searched many post for sending mails. I am trying to create a mail sender service. I tried two methods.
Method 1:
public class MailSender : IMailSender
{
public async Task SendMail(string to = null, string title = null, string body = null)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("mygmail#gmail.com", "password"),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network
};
client.SendAsync("mygmail#gmail.com", to, title, body, "mail send success");
}
}
Method 2:
public class MailSender : IMailSender
{
public async Task SendMail(string to = null, string title = null, string body = null)
{
MailAddress sender = new MailAddress("mygmail#gmail.com");
MailAddress reciver = new MailAddress(to);
MailMessage message = new MailMessage();
message.From = sender;
message.To.Add(reciver);
message.Subject = title;
message.Body = body;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential()
{ Password = "password", UserName = "mygmail#gmail.com" };
await smtp.SendMailAsync(message);
}
}
I don't know why its not working. There are no exceptions thrown, and all Google security setting are set.
guys i don't know why it wasnt work earlier
but i rewrite the code like this and it worked sorry
namespace MyShop.Services
{
public class MailSender : IMailSender
{
public async Task SendMail(string FromApp,string ToUser, string Title, string MailBody,string Password)
{
SmtpClient smtpClient = new("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential(FromApp, Password),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network
};
MailMessage mail = new
MailMessage(FromApp,ToUser ,Title ,MailBody);
smtpClient.SendAsync(mail, null);
}
}
}

converting to system.net.mail.mailMessage error

i'm actually trying to create registration page with verfication mail using MVC in visual studio, but here to send a message im getting
error : 'RandLform.Controllers.MailMessage' to 'System.Net.Mail.MailMessage' RandLform
public void SendVerficationLinkEmail(string emailID, string activationCode)
{
var VerifyUrl = "/User/VerifyAccount/" + activationCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, VerifyUrl);
var fromEmail = new MailAddress("lokeshkingdom4u#gmail.com", "Lokesh Pladugula");
var toEmail = new MailAddress(emailID);
var fromEmailPassword = "paisa007";
string subject = "Account created Succesfully!";
string body = "<br/>To verify your account, click on below link.<br/><br/> "+" "+link+"";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NewNetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
Lokesh Paladugula,
I recommend you to change password of your email account.
I'm not sure if this is actual error, please send proper error.

Asp.net sending email

How can I send an activation email when new users register in my website using asp.net c#? I have tried the steps described
this link but I have faced this error:
System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
Is there any solution to this or any other way to send an email?
this is my code
using (MailMessage mm = new MailMessage("sender#gmail.com", txtEmail.Text))
{
mm.Subject = "Account Activation";
string body = "Hello " + txtUsername.Text.Trim() + ",";
body += "<br /><br />Please click the following link to activate your account";
body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
body += "<br /><br />Thanks";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("sender#gmail.com", "<password>");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
The proposed duplicate did not solve the problem. I am already using port 587.
See the code below:
public static class email_utility
{
public static async Task<bool> send_email(this string body, string subject, string email, int try_count)
{
return await Task.Run(() =>
{
var cli = new SmtpClient();
using (var message = new MailMessage(config.sender_email, email))
{
message.Subject = subject;
message.SubjectEncoding = UTF8Encoding.UTF8;
message.Body = body;
message.BodyEncoding = UTF8Encoding.UTF8;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
for (var count = 0; count < try_count; ++count)
{
try
{
lock (config.sender_email)
{
cli.Send(message);
return true;
}
}
catch (SmtpFailedRecipientsException)
{
return false;
}
catch (SmtpException)
{
Thread.Sleep(config.send_timeout);
}
}
return false;
}
});
}
}
Try this, it works perfectly and you only have to change the fields that are before the var smtp = newSMTPCient.
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);
}

Getting smtpException when attemping to send mail C#

I'm trying to send an email through SmtpClient using this code
var client = new SmtpClient("smtp.gmail.com", 465)
{
Credentials = new NetworkCredential("***#gmail.com", "password"),
EnableSsl = true,
};
client.Send("***#gmail.com", "***#gmail.com", "test", "testbody");
What I'm getting is smtpException "Message could not be sent".
System.Net.Mail.SmtpException: Message could not be sent. ---> System.Exception:Connectionclosed at System.Net.Mail.SmtpClient.Read () [0x000f9] in /private/tmp/source/bockbuild-mono-
I'm using Mono on Mac (OSX 10.9.2)
My credentials and host/port are correct.
Maybe I need to enable it through my gmail account somehow?
Thanks!
Use:
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);
}

SmtpClient cannot send email

I try two application, one in java and one in C#. The java application can send email successfully but the C# cannot. Here is the two apps :
1.Java
final String username = "myaccount#mydomain";
final String password = "mypassword";
String smtpHost = "smtp.mydomain";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(username));
message.setSubject("Test send email");
message.setText("Hi you!");
Transport.send(message);
2.C#
string username = "myaccount#mydomain";
string password = "mypassword";
string smtpHost = "smtp.mydomain";
SmtpClient mailClient = new SmtpClient(smtpHost, 465);
mailClient.Host = smtpHost;
mailClient.Credentials = new NetworkCredential(username, password);
mailClient.EnableSsl = true;
MailMessage message = new MailMessage(username, username, "test send email", "hi u");
mailClient.Send(message);
So, what is the mistake i made in C# application? Why it cannot send email?
EDIT:
I have read this question How can I send emails through SSL SMTP with the .NET Framework? and it works. The deprecated System.Web.Mail.SmtpMail works but System.Net.Mail.SmtpClient doesn't. Why ?
3.This C# code work fine :
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver","smtp.mydomain");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "myaccount#mydomain");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mypassword");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
myMail.From = "myaccount#mydomain";
myMail.To = "myaccount#mydomain";
myMail.Subject = "new code";
myMail.BodyFormat = System.Web.Mail.MailFormat.Html;
myMail.Body = "new body";
System.Web.Mail.SmtpMail.SmtpServer = "smtp.mydomain:465";
System.Web.Mail.SmtpMail.Send(myMail);
The .NET System.Net.Mail.SmtpClient class cannot handle implicit SSL connection. Implicit SSL connections are sent over Port 465, as the client is configured in your example.
You can use a third party library like AIM (Aegis Implicit Mail) to send implicit SSL messages.
You can try this code as well. Also sends the email in a seperate thread.
using System.Net.Mail;
public static void Email(string Content, string To, string Subject, List<string> Attach = null, string User = "sender#sender.com", string Password = "MyPassword", string Host = "mail.sender.com", ushort Port = 587, bool SSL = false)
{
var Task = new System.Threading.Tasks.Task(() =>
{
try
{
MailMessage Mail = new MailMessage();
Mail.From = new MailAddress(User);
Mail.To.Add(To);
Mail.Subject = Subject;
Mail.Body = Content;
if (null != Attach) Attach.ForEach(x => Mail.Attachments.Add(new System.Net.Mail.Attachment(x)));
SmtpClient Server = new SmtpClient(Host);
Server.Port = Port;
Server.Credentials = new System.Net.NetworkCredential(User, Password);
Server.EnableSsl = SSL;
Server.Send(Mail);
}
catch (Exception e)
{
MessageBox.Show("Email send failed.");
}
});
Task.Start();
}

Categories

Resources