I'm working in an application which sends the mail from server. since smtp.send(msg) will take some time to communicate with the server. i had made the send code block in separate thread. It worked fine before, but after adding the timer control timer1( which was doing some code logic). The mail send was interrupted due to the following error :
Unable to evaluate expression because the code is optimized or a
native frame is on top of the call stack
Threading comes here..
void sendMail()
{
ThreadStart sendCreateMail = delegate() { Send(subject); };
Thread threadSendCreateMail = new Thread(sendCreateMail);
sendCreateMail.IsBackground = true;
sendCreateMail.Start();
timer1.Enabled = true;
}
net.mail code comes here....
protected void Send(string subject)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient("smtp.office365.com");
var credential = (System.Net.NetworkCredential)smtp.Credentials;
string Username = credential.UserName;
string password = credential.Password;
mail.From = new MailAddress(Username);
mail.To.Add(toMail);
mail.Subject = "subject";
mail.Body = "msg body";
mail.IsBodyHtml = true;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(Username, password);
smtp.Send(mail);
}
UPDATE
The sendMail task works in other pages. Here it is a popup so that timer1 block which i already told is doing a popup close function. There it is stopping the execution of thread. that i can understand (like response.end, response.redirect can't guess what exactly, its a third party tool called telerik radwindow!). but how to overcome this.
this is what i use in my application
SmtpClient client = new SmtpClient();
client.Port = your port;
client.Host = your host;
client.EnableSsl = true;
client.Timeout = 15000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(your username, your passowrd);
MailMessage mm = new MailMessage(your username, recepient[0], title, message);
for (int a = 1; a < recepient.Count; a++)
mm.To.Add(recepient[a]);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.SendCompleted += (s, e) =>
{
client.Dispose();
mm.Dispose();
};
client.SendAsync(mm, null);
Related
My Xamarin app's release version is being tested by a non-developer, which sometimes means the tester has trouble communicating to me the details of bugs they encounter.
I'd like to implement some code that will execute whenever a crash or error occurs, and send an email to my address with the error information to help my debugging. I've written an email method (see below) but I'd like to know how I can call it whenever an unhandled exception is thrown rather than wrapping every single possible method in a try-catch.
public static void Email(string htmlString)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
msg.From = new MailAddress("email here");
msg.To.Add(new MailAddress("other email here"));
msg.Subject = "Error Report";
msg.IsBodyHtml = true;
msg.Body = htmlString;
smtp.Port = 1234;
smtp.Host = "smtp here";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("email", "password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(msg);
}
catch (Exception)
{
}
}
The basic way to catch errors in Xamarin apps is by using a try/catch block. Try/catch is easy to get.
You could do something like below.
private void Send_Clicked(object sender, EventArgs e)
{
try
{
.......
}
catch(Exception ex)
{
Email(ex.ToString());
}
}
public static void Email(string htmlString)
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
msg.From = new MailAddress("email here");
msg.To.Add(new MailAddress("other email here"));
msg.Subject = "Error Report";
msg.IsBodyHtml = true;
msg.Body = htmlString;
smtp.Port = 1234;
smtp.Host = "smtp here";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("email", "password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(msg);
}
Xamarin(Mono) internally "handles" those uncaught exceptions by surrounding literally everything with try-catch and raising the Unhandled event.
Explanation from the thread. Struggling to understand Xamarin exception handling
You could check the link. It provides a way to get the error log from log File.
Exceptions when using Xamarin Android
MailMessage msg = new MailMessage("teunenrichard#gmail.com", "ipadcraze#hotmail.com", "Movies this month", "Hello this is a test mail");
msg.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
NetworkCredential xre = new System.Net.NetworkCredential("teunenrichard#gmail.com", "Password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = xre;
smtp.EnableSsl = true;
smtp.Send(msg);
This is the code i run in a form . load to do a test email but it will not rund and says operation timed out. ive tried everything please help
MessageBox.Show("mail sent");
Use the "Timeout" property for your Smtp client . I think 0 is max
smtp.Timeout = 0;
For better Understanding of the error message try putting your code in a Try-Catch Block and then see the inner exception of the catch in MessageBox.Show(). It might provide you some more information regarding the error and might help/guide you in the right direction to resolve it. Something like below:-
try
{
//your email sending logic
}
catch(Exception ex)
{
MessageBox.Show(ex.InnerException.ToString());
}
You should send your mails using background thread, so as to make sure that your UI thread does not block and returns immediately. You can do something like this
private async void sendButton_Click(object sender, EventArgs e)
{
var result = await SendMail();
if (result)
{
MessageBox.Show("Mail sent");
}
}
private Task<bool> SendMail()
{
var task = Task.Run<bool>(() =>
{
MailMessage msg = new MailMessage("sendermail#gmail.com", "recievermail#gmail.com", "Movies this month", "Hello this is a test mail");
msg.IsBodyHtml = false;
using(SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.UseDefaultCredentials = false;
NetworkCredential xre = new NetworkCredential("sendermail#gmail.com", "Password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = xre;
smtp.EnableSsl = true;
smtp.Send(msg);
return true;
}
});
return task;
}
I have been trying for a long time to send a mail from a Gmail account to a gmail account using the below code.
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 = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
After the execution reaches "smtp.Send(mm)" the browser says waiting and after 2 minutes I get the exception saying "Failure Sending Email"
And the following Error message
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond ...:587" (some IP)
I have searched a lot for this but haven't found a solution. Please help me solve this issue.
Thank you.
Try This One.
public static string SendMail(string stHtmlBody, string stSubject, string stToEmailAddresses)
{
string stReturnText = string.Empty;
try
{
if (!string.IsNullOrEmpty(stToEmailAddresses))
{
//Set SmtpClient to send Email
string stFromUserName = "fromusername";
string stFromPassword ="frompassword";
int inPort = Convert.ToInt32(587);
string stHost = "smtp.gmail.com";
bool btIsSSL =true;
MailAddress to = new MailAddress(stToEmailAddresses);
MailAddress from = new MailAddress("\"" + "Title" + "\" " + stFromUserName);
MailMessage objEmail = new MailMessage(from, to);
objEmail.Subject = stSubject;
objEmail.Body = stHtmlBody.ToString();
objEmail.IsBodyHtml = true;
objEmail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
System.Net.NetworkCredential auth = new System.Net.NetworkCredential(stFromUserName, stFromPassword);
client.Host = stHost;
client.Port = inPort;
client.UseDefaultCredentials = false;
client.Credentials = auth;
client.EnableSsl = btIsSSL;
client.Send(objEmail);
return stReturnText;
}
}
catch (Exception ex)
{
}
return stReturnText;
}
First of all, I think you should use
UseDefaultCredentials = false;
And
smtp.DeliveryMethod = SmtpDeliveryMethod.Network
You also need to allow less secure apps to access your account
I had a similar attempt but using Java. I was not successful doing that after a lot of search. I then used the Yahoo! SMTP, which worked very easily. Maybe you can try that.
I have an console app and I am trying to send mail from it.
My code.
MailMessage message = new MailMessage(MailSender, "ToMe#me.com");
message.Subject = "Using the new SMTP client.";
message.Body = #"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
try
{
client.Send(message);
}
catch (Exception ex)
{
string t = ex.Message;
}
Got this from here
I must be missing something since I am getting:
Failure sending mail.
What am I doing wrong here?
EDIT:
inner Exeption.
InnerException = {"The remote name could not be resolved:
'smtp.google.com'"}
You can try to use
smtp.gmail.com
instead of
smtp.google.com
Also try to make sure that you are providing the correct credentials along with the correct port. A server parameter info:
Source
So you can try something like this
MailMessage message = new System.Net.Mail.MailMessage();
string fromEmail = "youremailaddress#xyz.com";
string password = "yourPassword";
string toEmail = "recipientemailaddress#abc.com";
message.From = new MailAddress(fromEmail);
message.To.Add(toEmail);
message.Subject = "Using the new SMTP client.";
message.Body = "Using this new feature, you can send an e-mail message from an application very easily.";
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
using(SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(fromEmail, password);
smtpClient.Send(message.From.ToString(), message.To.ToString(), message.Subject, message.Body);
}
#Ra3IDeN ...hey brother try this...
SmtpClient smtpClient = new SmtpClient("mail.yourwebsitename.com", 25);
smtpClient.Credentials = new System.Net.NetworkCredential("demo#yourwebsitename.com.com", "yourIdPassword");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//code for: From ,CC & To
mail.From = new MailAddress("demo#yourwebsitename.com", "yourwebsite");
mail.To.Add(new MailAddress("demo#yourwebsitename.com"));
mail.CC.Add(new MailAddress("youremailid#gmail.com"));
smtpClient.Send(mail);
If you're trying to send email from a console application (your higher-level problem), I recommend using PostMark. Why:
NuGet - You can get the PostMark NuGet package and send email with a nice API. Convenient and simple.
Not marked as SPAM - You can configure your "server" with verification (including spf and signing). So your email will more likely reach the destination in their inbox rather than their SPAM box.
Free - to a point. I think it's 1000 emails for free then $1 per 1000. So that's pretty good. Compare that to any other vanilla SMTP server for rent. PostMark is cheap
Consistent - From Workstation DEV to server LIVE, the PostMark API is consistently accessible. I cannot stress how good that is. Often a server host will offer SMTP server endpoint but it will only work from inside their network, meaning you have to configure another SMTP server when you're doing DEV work on your workstation (or it simply wont work).
Async Interface - I'm not sure if built-in smtp client in .Net is async...
Tracking - Hey look at that, they have a tracking feature built-in. That's snazzy.
Example code for sending (source):
var message = new PostmarkMessage()
{
To = "recipient#example.com",
From = "sender#example.com",
TrackOpens = true,
Subject = "A complex email",
TextBody = "Plain Text Body",
HtmlBody = "<html><body><img src=\"cid:embed_name.jpg\"/></body></html>",
Tag = "business-message",
Headers = new HeaderCollection{
{"X-CUSTOM-HEADER", "Header content"}
}
};
var imageContent = File.ReadAllBytes("test.jpg");
message.AddAttachment(imageContent, "test.jpg", "image/jpg", "cid:embed_name.jpg");
var client = new PostmarkClient("server token");
var sendResult = await client.SendMessageAsync(message);
MailMessage msg = new MailMessage("YourEmail#gmail.com", "DestinationEmail#something.com");
msg.Subject = message.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("Message Content here as HTML", null, MediaTypeNames.Text.Html));
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", Convert.ToInt32( 587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("YourEmail#gmail.com", "YourPassword");
smtpClient.EnableSsl = true;
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object s,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
};
smtpClient.Credentials = credentials;
smtpClient.Send(msg);
I want to send a email through gmail server. I have put the following code but it is getting stuck while sending. Any idea please....
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("apps#xxxx.com");
//create instance of smtpclient
SmtpClient smtp = new SmtpClient();
smtp.Port = 465;
smtp.UseDefaultCredentials = true;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
//recipient address
mail.To.Add(new MailAddress("yyyy#xxxx.com"));
//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";
mail.Body = st;
smtp.Send(mail);
The xxxx.com is a mail domain in Google apps.
Thanks...
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("apps#xxxx.com");
// The important part -- configuring the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Port = 587; // [1] You can try with 465 also, I always used 587 and got success
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this
smtp.UseDefaultCredentials = false; // [3] Changed this
smtp.Credentials = new NetworkCredential(mail.From, "password_here"); // [4] Added this. Note, first parameter is NOT string.
smtp.Host = "smtp.gmail.com";
//recipient address
mail.To.Add(new MailAddress("yyyy#xxxx.com"));
//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";
mail.Body = st;
smtp.Send(mail);
I tried the above C# code to send mail from Gmail to my Corporate ID. While executing the application the control stopped indefinitely at the statement smtp.Send(mail);
While Googling, I came across a similar code, that worked for me. I am posting that code here.
class GMail
{
public void SendMail()
{
string pGmailEmail = "fromAddress#gmail.com";
string pGmailPassword = "GmailPassword";
string pTo = "ToAddress"; //abc#domain.com
string pSubject = "Test From Gmail";
string pBody = "Body"; //Body
MailFormat pFormat = MailFormat.Text; //Text Message
string pAttachmentPath = string.Empty; //No Attachments
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
SmtpMail.SmtpServer = "smtp.gmail.com:465";
SmtpMail.Send(myMail);
}
}
Set
smtp.UseDefaultCredentials = false
and use
smtp.Credentials = new NetworkCredential(gMailAccount, password);
This have worked for me:
MailMessage message = new MailMessage("myemail#gmail.com", toemail, subjectEmail, comments);
message.IsBodyHtml = true;
try {
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Timeout = 2000;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassord");
client.Send(message);
message.Dispose();
client.Dispose();
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
}
BUT (as of the time of this writing - Oct 2017)
You need to ENABLE "Allow less secure apps" inside the option "apps with account access" at the "My account" google security/privacy settings (https://myaccount.google.com)
I realise this is an answer to a very old question, with lots of other good answers. I am posting this code to include some of the useful comments posted by other users such as Using Statements and newer methods where some answers have obsolete methods. This code was tested and working as of 11 July 2018.
If sending via your GMail Account ensure that Allow less secure apps is enabled from your control panel
Class Code C#:
public class Email
{
public void NewHeadlessEmail(string fromEmail, string password, string toAddress, string subject, string body)
{
using (System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage())
{
myMail.From = new MailAddress(fromEmail);
myMail.To.Add(toAddress);
myMail.Subject = subject;
myMail.IsBodyHtml = true;
myMail.Body = body;
using (System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587))
{
s.DeliveryMethod = SmtpDeliveryMethod.Network;
s.UseDefaultCredentials = false;
s.Credentials = new System.Net.NetworkCredential(myMail.From.ToString(), password);
s.EnableSsl = true;
s.Send(myMail);
}
}
}
}
Class Code VB:
Public Class Email
Sub NewHeadlessEmail(fromEmail As String, password As String, toAddress As String, subject As String, body As String)
Using myMail As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
myMail.From = New MailAddress(fromEmail)
myMail.To.Add(toAddress)
myMail.Subject = subject
myMail.IsBodyHtml = True
myMail.Body = body
Using s As New Net.Mail.SmtpClient("smtp.gmail.com", 587)
s.DeliveryMethod = SmtpDeliveryMethod.Network
s.UseDefaultCredentials = False
s.Credentials = New Net.NetworkCredential(myMail.From.ToString(), password)
s.EnableSsl = True
s.Send(myMail)
End Using
End Using
End Sub
End Class
Usage C#:
{
Email em = new Email();
em.NewHeadlessEmail("myemail#gmail.com", "password", "recipient#email.com", "Subject Text", "Body Text");
}
Usage VB:
Dim em As New Email
em.NewHeadlessEmail("myemail#gmail.com", "password", "recipient#email.com", "Subject Text", "Body Text")
Use Port number 587
With the following code, it will work successfully.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("abc#mydomain.com", "Enquiry");
mail.To.Add("abcdef#yahoo.com");
mail.IsBodyHtml = true;
mail.Subject = "Registration";
mail.Body = "Some Text";
mail.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
//smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("xyz#gmail.com", "<my gmail pwd>");
smtp.EnableSsl = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
But, there is a problem with using gmail. The email will be sent successfully, but the recipient inbox will have the gmail address in the 'from address' instead of the 'from address' mentioned in the code.
To solve this, please follow the steps mentioned at the following link.
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
before following all the above steps, you need to authenticate your gmail account to allow access to your application and also the devices. Please check all the steps for account authentication at the following link:
http://karmic-development.blogspot.in/2013/11/allow-account-access-while-sending.html
ActiveUp.Net.Mail.SmtpMessage smtpmsg = new ActiveUp.Net.Mail.SmtpMessage();
smtpmsg.From.Email = "abcd#test.com";
smtpmsg.To.Add(To);
smtpmsg.Bcc.Add("vijay#indiagreat.com");
smtpmsg.Subject = Subject;
smtpmsg.BodyText.Text = Body;
smtpmsg.Send("mail.test.com", "abcd#sss.com", "user#1234", ActiveUp.Net.Mail.SaslMechanism.Login);
simple code works
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com",587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(address, password);
smtp.Send(mail);