Problems with sending an email - c#

I am working with C# and I am trying to send an email form a web page. I am trying to populate the from email address from a textbox and the to email address is being hard coded. My code is as follows and the errors I am getting are after the code.
try
{
MailMessage oMsg = new MailMessage();
// TODO: Replace with sender e-mail address. Get from textbox: string SenderEmail = emailbox.text
oMsg.From = emailbox.Text; //Senders email
// TODO: Replace with recipient e-mail address.
oMsg.To = "DummyRecipient#gmail.com"; //Recipient email
oMsg.Subject = subjecttbox.Text; //Subject of email
// SEND IN HTML FORMAT (comment this line to send plain text).
//oMsg.BodyFormat = MailFormat.Html;
// HTML Body (remove HTML tags for plain text).
oMsg.Body = EmailBody; //Body of the email
// ADD AN ATTACHMENT.
// TODO: Replace with path to attachment.
//String sFile = #"C:\temp\Hello.txt";
//MailAttachment oAttch = new MailAttachment(sFile, MailEncoding.Base64);
//oMsg.Attachments.Add(oAttch);
// TODO: Replace with the name of your remote SMTP server.
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
//SmtpMail.SmtpServer = "Smtp.gmail.com"; //Email server name, Gmail = Smtp.gmail.com
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("DummySenderAddress#gmail.com", "DummyPassword");
SmtpServer.EnableSsl = true;
SmtpMail.Send(oMsg);
oMsg = null;
//oAttch = null;
}
catch //(Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
Cannot implicitly convert type 'string' to
'System.Net.Mail.MailAddress' Property or indexer
'System.Net.Mail.MailMessage.To' cannot be assigned to -- it is read
only
Cannot implicitly convert type 'string' to
'System.Net.Mail.MailAddressCollection' The name 'SmtpMail' does not
exist in the current context

The problem is in your line:
oMsg.To = "DummyRecipient#gmail.com"; //Recipient email
Emails can have more than one recipient. Therefore the "To" property of the MailMessage class is a collection. Not a single email address.
Additionally, you need to create a MailAddress object instead of just using a string for the email.
Use the following line instead of the above.
oMsg.To.Add(new MailAddress("DummyRecipient#gmail.com")); //Recipient email

oMsg.From takes a MailAddress object as its input, not a string. Replace it with:
oMsg.From = new MailAddress(emailbox.Text);
oMsg.To takes a MailAddressCollection as its input. Assuming that collection isn't null, you should be able to replace it with:
oMsg.To.Add("DummyRecipient#gmail.com");

Related

Wrong email titles when sending mails multiple times

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.

From Address Shows NetworkCredential User Email

I have made an web application for sending e-mail. It works fine.
The problem is receiver end - Receiver shows NetworkCredential User Email as From Email.
And the email provided as From Email doesn't exist.
i want to show the suplied email not the networkcredential user email to the receiver.
sample code-
using System.Net.Mail;
MailMessage oMsg = new MailMessage();
oMsg.From = new MailAddress("sender#somewhere.com","Diplay Name");
oMsg.To.Add(new MailAddress("recipient#somewhere.com"));
oMsg.Subject = "Send Using Web Mail";
oMsg.Body ="Hi..";
System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient("host", port_no);
System.Net.NetworkCredential nc = new System.Net.NetworkCredential("user", "password");
s.EnableSsl = true;
s.UseDefaultCredentials = false;
s.Credentials = nc;
s.Send(oMsg);
The receiver gets from email is "user" but i want to show "sender#somewhere.com".
I think you need to update the Display name of the e-mail address that you send from.
Update oMsg.From = new MailAddress("sender#somewhere.com"); to be oMsg.From = new MailAddress("sender#somewhere.com","sender#somewhere.com");
MailAddress has an overload which allows you to pass is a display name for the given mail addres e.g. new MailAddress("sender#somewhere.com", "Display Name");
Some mail services (such as google), override the .FROM value, and will always use the ENVELOPE value, which is the NetworkCredential username.
I have a feeling that is what you are seeing.

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).

How to send email in richtext format to Outlook?

It works great to send emails (to Outlook) in HTML format by assigning the text/html content type string like so:
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("--#---.com");
message.ReplyTo = new MailAddress("--#---.com");
message.To.Add(new MailAddress("---#---.com"));
message.Subject = "This subject";
message.Body = "This content is in plain text";
message.IsBodyHtml = false;
string bodyHtml = "<p>This is the HTML <strong>content</strong>.</p>";
using (AlternateView altView = AlternateView.CreateAlternateViewFromString(bodyHtml,
new ContentType(MediaTypeNames.Text.Html)))
{
message.AlternateViews.Add(altView);
SmtpClient smtp = new SmtpClient(smtpAddress);
smtp.Send(message);
}
}
The email is correctly recognized as HTML in Outlook (2003).
But if I try rich text:
MediaTypeNames.RichText;
Outlook doesn't detect this, it falls back to plain text.
How do I send email in rich text format?
The bottom line is, you can't do this easily using System.Net.Mail.
The rich text in Outlook is sent as a winmail.dat file in the SMTP world (outside of Exchange).
The winmail.dat file is a TNEF message. So, you would need to create your richtext inside of the winmail.dat file (formatted to TNEF rules).
However, that's not all. Outlook uses a special version of compressed RTF, so, you would also need to compress your RTF down, before it's added to the winmail.dat file.
The bottom line, is this is difficult to do, and unless the client really, really needs this functionality, I would rethink it.
This isn't something you can do with a few lines of code in .NET.
You can also achieve this by adding another alternate view before your calendar view as below:
var body = AlternateView.CreateAlternateViewFromString(bodyHtml, new System.Net.Mime.ContentType("text/html"));
mailMessage.AlternateViews.Add(body);
This worked for me..
public void sendUsersMail(string recipientMailId, string ccMailList, string body, string subject)
{
try
{
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("norepl#xyz.com", "Tracker Tool");
Msg.To.Add(recipientMailId);
if (ccMailList != "")
Msg.CC.Add(ccMailList);
Msg.Subject = subject;
var AltBody = AlternateView.CreateAlternateViewFromString(body, new System.Net.Mime.ContentType("text/html"));
Msg.AlternateViews.Add(AltBody);
Msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("mail.xyz.com");
smtp.Send(Msg);
smtp.Dispose();
}
catch (Exception ex)
{
}
}

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