Wrong email titles when sending mails multiple times - c#

First of all, my apologies if this is a duplicate question. I have searched for it a lot, but couldn't find related issues.
So here's the problem: I am using SmtpClient and MailMessage class to send mails. I am passing the subject of the mail as a parameter in the mail sending method. First time the mail is sent with the proper subject (the one i sent as parameter). However, in all next emails, no matter what subject i put, the subject remains the same (the one used first time). The subject is set from inside of the method.
(Note: This is a WindowsForm application)
What i have tried is, creating another method named "Refresh()" which disposes the mail object and creates it again (with from and to info only). And call this method each time after a mail is sent. But it doesn't help with this problem.
Codes are given below:
Fields:
MailMessage message;
SmtpClient mailer;
string from = "sender email";
string pass = "sender pass";
string to = "rec email";
Constructor:
try
{
message = new MailMessage(from, to);
mailer = new SmtpClient("smtp.gmail.com", 587);
mailer.Credentials = new NetworkCredential(from, pass);
mailer.EnableSsl = true;
}
catch(Exception ex) { /*code to write log*/ }
Refresh method:
void RefreshMessage()
{
try
{
message.Subject = "";
message.Dispose();
message = new MailMessage(from, to);
}
catch(Exception ex) { /*write log*/ }
}
Method which is sending the mail:
internal void TextOnly(string sub, string bodyMessage)
{
try
{
message.Subject = sub;
message.Body = bodyMessage;
mailer.Send(message);
this.RefreshMessage();
}
catch (Exception ex) { /*write log*/ }
}
Example of how it's called:
m.TextOnly("Subject 1" , SomeStringMethod());
m.TextOnly("Another Title " + anyString, "Some string mail");
m.TextOnly("[TAG] Email subject goes here" , AnotherStringMethod());
Now no matter whatever subject is sent in the parameter, it will always send with subject "Subject 1" (from the example above). The body of the message is fine, only the subject is not right.
I have few other methods in the class (for other purposes like sending mails with attachments for example), where subject isn't passed as parameter but it's set directly from within the method (like message.Subject = "Example Sub" from within the method), in that case it works fine.
But in the case above, where the subject is passed to the method, the subject remains the same.

Like the comment section already stated, there is no reason to cache the message itself. Currently, you're disposing the message(which actually puts it in a unusable state) and then you recreate it. Check out more HERE. You can just as well simply create new objects and dispose of them after you're done so the Garbage Collector can release the resources as soon as possible.
Just utilize a simple method for constructing MailMessages and send them directly.
internal MailMessage ConstructTextMailMessage(MailAddress from, MailAddress to, string subject, string body)
{
return ConstructTextMailMessage(from.Address, to.Address, subject, body);
}
internal MailMessage ConstructTextMailMessage(string from, string to, string subject, string body)
{
return new MailMessage(from, to, subject, body);
}
And then:
var mailClient = new SmtpClient("smtp.gmail.com", 587);
mailClient.Credentials = new NetworkCredential(from, pass);
mailClient.EnableSsl = true;
mailClient.Send(ConstructTextMailMessage(from, to, "Subject 1", SomeStringMethod()));
mailClient.Send(ConstructTextMailMessage(from, to, "Another Title " + anyString, "Some string mail");
mailClient.Send(ConstructTextMailMessage(from, to, "[TAG] Email subject goes here", AnotherStringMethod());
If you have attachments in the MailMessage, you should call Dispose after using them to clear up the streams. Also, call Dispose on the SmtpClient when you're done using it.

I used the same functionality (SntpClient, MailMessage etc.) in one of my programms and it worked just fine:
SmtpClient client = new SmtpClient("host", port);
MailMessage mail;
MailAddress absender = new MailAddress("mail#adress.from");
foreach (string sub in Subjects)
{
mail = new MailMessage();
mail.IsBodyHtml = true;
mail.Subject = sub;
mail.From = absender;
mail.To.Add("mail#adress.to");
client.Send(mail);
}
Mybe you just need to make a new MailMessage-Object each time you "create" a E-Mail.

Related

Configure forward-to property for MailMessage like replyto in C#

Is there any way to configure forward-to email address like replyto in System.Net.Mail.MailMessage?
If not then is there any way I can achieve that?
No, there is not.
The reason is that there is no such field defined in an email. You can see the defined fields here.
So this is not a matter of C# API, there is no way to do what you want to do, not in C# and not in other languages/frameworks.
You can do this only by doing it via Outlook (using interop)
var newItem = mailItem.Forward();
newItem.Recipients.Add("test#test.be");
newItem.Send();
the .Forward() is described here
There's no 'forwardto' in MailMessage (that's up to the user receiving the mail).
But you can send to multiple receipients at once, using either the CC or the BCC properties.
Here's an axample using CC:
public static void CreateCopyMessage(string server)
{
MailAddress from = new MailAddress("ben#contoso.com", "Ben Miller");
MailAddress to = new MailAddress("jane#contoso.com", "Jane Clayton");
MailMessage message = new MailMessage(from, to);
// message.Subject = "Using the SmtpClient class.";
message.Subject = "Using the SmtpClient class.";
message.Body = #"Using this feature, you can send an email message from an application very easily.";
// Add a carbon copy recipient.
MailAddress copy = new MailAddress("Notification_List#contoso.com");
message.CC.Add(copy);
SmtpClient client = new SmtpClient(server);
// Include credentials if the server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Console.WriteLine("Sending an email message to {0} by using the SMTP host {1}.",
to.Address, client.Host);
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateCopyMessage(): {0}",
ex.ToString() );
}
}
Now you can send to more than one, which Works like auto forwarding.

Change sender name doesn't work

First of all, I search for an hour how to solve my problem on other posts but the other solutions don't work in my case.
My problem
I need to send a report mail after the execution of my program. To send mails I use System.Net.Mail namespace and particularly SmtpClient class.
The mail is correctly sent but I need to hide the sender mail address.
I tried some different things but none of them seems to work.
What I tried
Firstly I tried to do this :
public static void sendMail(String Titre,String Message)
{
SmtpClient client = new SmtpClient(GestionParametres.getParametre("SMTP"), Int32.Parse(GestionParametres.getParametre("PortSmtp")));
client.Credentials = new System.Net.NetworkCredential(GestionParametres.getParametre("UsernameSmtp"), GestionParametres.getParametre("PasswordSmtp"));
MailAddress from = new MailAddress(GestionParametres.getParametre("ExpediteurMail"),"Rapport interface ****");
MailAddress to = new MailAddress(GestionParametres.getParametre("DestinataireMail"));
MailMessage message = new MailMessage(GestionParametres.getParametre("ExpediteurMail"), GestionParametres.getParametre("DestinataireMail"));
message.From = from;
message.Subject = Titre;
message.Body = Message;
message.BodyEncoding = System.Text.Encoding.UTF8;
client.Send(message);
}
But the sender mail address still appear in mail.
Secondly, I tried this :
public static void sendMail(String Titre,String Message)
{
SmtpClient client = new SmtpClient(GestionParametres.getParametre("SMTP"), Int32.Parse(GestionParametres.getParametre("PortSmtp")));
client.Credentials = new System.Net.NetworkCredential(GestionParametres.getParametre("UsernameSmtp"), GestionParametres.getParametre("PasswordSmtp"));
MailAddress from = new MailAddress(GestionParametres.getParametre("ExpediteurMail"));
MailAddress to = new MailAddress(GestionParametres.getParametre("DestinataireMail"));
MailMessage message = new MailMessage("Rapport interface ****" + GestionParametres.getParametre("ExpediteurMail"), GestionParametres.getParametre("DestinataireMail"), Titre, Message);
client.Send(message);
}
But it doesn't work either...
Now I have no idea how to solve this problem.
Any idea ?
Thank you in advance,
Thomas

using gmail as smpt for deliver email from mvc controller

I'm trying to send email from asp.net mvc controller. Gmail account used here for smpt is configured to use with less security, so that's not the problem here.
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
I'm using code
var text = "email body to deliver";
SendEmail("mydeliverEmailAddress#gmail.com", text);
public static bool SendEmail(string SentTo, string Text)
{
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPass");
client.Port = 465;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
MailAddress
maFrom = new MailAddress("sender_email#domain.tld", "Sender's Name", Encoding.UTF8),
maTo = new MailAddress(SentTo, "Recipient's Name", Encoding.UTF8);
MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
mmsg.IsBodyHtml = true;
mmsg.Subject = "Some Other Text as Subject";
mmsg.SubjectEncoding = Encoding.UTF8;
client.Send(mmsg);
}
catch (Exception ex)
{
}
return true;
}
Wait a minute. You are using your gmail account: myemail#gmail.com and trying to send an email on behalf of sender_email#domain.tld?
For more than obvious reasons that's never gonna work. So make sure that you are using the same email address as the one you are authenticating against:
maFrom = new MailAddress("myemail#gmail.com", "Sender's Name", Encoding.UTF8),
You can only send emails from the account you are authenticated against. Of course the recipient email can be any address that gmail can deliver to.
You've got another issue with your code. You are using a wring port here:
client.Port = 465;
The correct port that gmail SMTP works with is the following:
client.Port = 587;
Also you might want to ensure that you have enabled less secure apps in your gmail account or you will not be able to use SmtpClient in .NET to send emails using this SMTP: https://www.google.com/settings/security/lesssecureapps?pli=1
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
What error message do you expect to get when you did the worst ever possible thing? You wrapped your code in a try/catch block and in your catch block you did absolutely nothing. You just consumed the exception:
catch (Exception ex)
{
}
So make sure that you do something useful with an exception if you are going to be catching it. For example something useful could be to log this exception and send an error message to the user saying that something bad happened and you couldn't send an email and that you are investigating the issue right now.
var smtpClient = new SmtpClient("YourSMTPServer", "SMTPServerPort"))
{
Credentials = new NetworkCredential("YourEmail",
"Password"),
EnableSsl = false
};
string fromEmail = "YourEmail";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmail);
mailMessage.To.Add("Recipient's EMail");
mailMessage.Subject = "Test Mail";
mailMessage.Body = "This is test Mail";
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);

How to check if the email have sent successfully or not?

See title. Since SmtpClient.Send has no return value, I want to know how I can be sure that the E-Mail was successfully sent.
Here is the code I have until now and it works fine (it is from google):
private void sendMail(string strToAddress, string strFromAddress, string strSubject, string strBody)
{
// new instance of MailMessage
MailMessage mailMessage = new MailMessage();
// Sender Address
mailMessage.From = new MailAddress(strFromAddress);
// Recepient Address
mailMessage.To.Add(new MailAddress(strToAddress));
// Subject
mailMessage.Subject = strSubject;
// Body
mailMessage.Body = strBody;
// format of mail message
mailMessage.IsBodyHtml = true;
// new instance of Smtpclient
SmtpClient mailSmtpClient = new SmtpClient("mail.lablabal.com");
// mail sent
mailSmtpClient.Send(mailMessage);
}
If there's an immediate error, SmtpClient::Send() will throw an exception. There's no way to "track" the email (unless there's some confirmation link to click or whatever). You won't keep a server connection till the mail is received, only till your smtp server passed it successfully (or failed doing so).

send smtp mail including html to gmail account

I've found this small code that sends email to gmail users. I'd like the body of the mail to contain html (for example, decoding a link for it to hold different text than the url it's pointing to).
I am using c# .net 3.5. I've used these classes in my code:
MailMessage
SmtpClient
How can this be done?
Here's a copy of my code:
MailMessage message = new MailMessage("me#gmail.com", WebCommon.UserEmail, "Test", context.Server.HtmlEncode("<html> <body> <a href='www.cnn.com'> test </a> </body> </html> "));
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("him#gmail.com", "myPwd");
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Port = 587;
smtp.Send(message);
Thanks!
Something like this should work:
Note that MailMessage refers to System.Net.MailMessage. There is also System.Web.MailMessage, which I have never used and -as far as I know- is obsolete.
MailMessage message = new MailMessage();
// Very basic html. HTML should always be valid, otherwise you go to spam
message.Body = "<html><body><p>test</p></body></html>";
// QuotedPrintable encoding is the default, but will often lead to trouble,
// so you should set something meaningful here. Could also be ASCII or some ISO
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
// No Subject usually goes to spam, too
message.Subject = "Some Subject";
// Note that you can add multiple recipients, bcc, cc rec., etc. Using the
// address-only syntax, i.e. w/o a readable name saves you from some issues
message.To.Add("someone#gmail.com");
// SmtpHost, -Port, -User, -Password must be a valid account you can use to
// send messages. Note that it is very often required that the account you
// use also has the specified sender address associated!
// If you configure the Smtp yourself, you can change that of course
SmtpClient client = new SmtpClient(SmtpHost, SmtpPort) {
Credentials = new NetworkCredential(SmtpUser, SmtpPassword),
EnableSsl = enableSsl;
};
try {
// It might be necessary to enforce a specific sender address, see above
if (!string.IsNullOrEmpty(ForceSenderAddress)) {
message.From = new MailAddress(ForceSenderAddress);
}
client.Send(message);
}
catch (Exception ex) {
return false;
}
For more sophisticated templating solutions that render the Body html rather than hard-codin it, there is, for example, the EMailTemplateService in MvcContrib which you can use as a guideline.
One way to do it is to create an alternate html view of the email:
MailMessage message = new MailMessage();
message.Body = //plain-text version of message
//set up message...
//create html view
string htmlBody = "<html>...</html>";
htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
message.AlternateViews.Add(htmlView);
//send message
smtpClient.Send(message);

Categories

Resources