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.
Related
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.
I have create function to send an email. This function was work successful on localhost but on server its failed without any exception. I know the problem comes from my Port on IP Address.
The sample body is string body = "<p>Please click here</p>Thank You."
The problem is : between IP Address and Port.
Successful send an email if i remove :.
Do you guys have any ideas?
public void Sent(string sender, string receiver, string subject, string body)
{
using (MailMessage mail = new MailMessage(sender, receiver))
{
using (SmtpClient client = new SmtpClient())
{
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "mail.companyName.com.my";
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
client.Send(mail);
}
}
}
You are doing it right, the code to send the mail is ok (you may want to revise the function name and make the smtp host name configurable, but that is not the point here).
The e-mail delivery fails on a relay, there is no immedieate feedback (no exception) to the client about this kind of failure.
The best bet is the IncreaseScoreWithRedirectToOtherPort property set in Set-HostedContentFilterPolicy in case your mail provider is Office365, or a similar spam filter mechanism in any other mail provider that is encountered down the mail delivery chain.
You can set a reply-to address and hope that the destination server will bounce a delivery failure that gives you more information. Or have the admin of the mail server look up the logs. More information here:
https://serverfault.com/questions/659861/office-365-exchange-online-any-way-to-block-false-url-spam
Try setting the 'mail.Body' to receive a Raw Html message instead of a encoded string, like:
mail.Body = new System.Web.Mvc.HtmlHelper(new System.Web.Mvc.ViewContext(), new System.Web.Mvc.ViewPage()).Raw(body).ToString();
Or put a using System.Web.Mvc at the beginning so it gets shorter and easier to understand:
using System.Web.Mvc
mail.Body = new HtmlHelper(new ViewContext(), new ViewPage()).Raw(body).ToString();
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);
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).
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);