I have written the below code to send an email wherein the message body is a html page.
I don't get any error when i run this code but do not get any mail. I tried putting body as simple message string then i received the email but not as message body as html page.
What is going wrong? please help.
protected void btnSend_Click(object sender, EventArgs e)
{
SendHTMLMail();
}
public void SendHTMLMail()
{
//var path = Server.MapPath("~/test/HTMLPage.htm");
StreamReader reader = new StreamReader(Server.MapPath("~/expo_crm/test/HTMLPage.htm"));
string readFile = reader.ReadToEnd();
string myString = "";
myString = readFile;
SmtpClient smtp = new SmtpClient
{
Host = "mail.abc.com", // smtp server address hereā¦
Port = 25,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential("abc#xyz.com", "xxxx"),
Timeout = 30000,
};
MailMessage message = new MailMessage("abc#xyz.com", "akshata#gmail.com", " html ", myString);
message.IsBodyHtml = true;
smtp.Send(message);
}
Most of the time mail server checks the html content and marks as SPAM mail based on the html tags like links, images etc in the mail. Make sure that you have low number of HTML tags probably no external links, images and try again to send mail.
Here is working code, if this helps
public void SendEmail(ListDictionary email)
{
try
{
var msg = new MailMessage {From = new MailAddress(_emailUsername, _emailFrom), BodyEncoding = Encoding.UTF8, Subject = Convert.ToString(email["SUBJECT"]), Priority = MailPriority.Normal};
//
var emailTo = (List<string>) email["TO"];
var emailCc = (List<string>) email["CC"];
var emailBcc = (List<string>) email["BCC"];
foreach (var to in emailTo.Where(to => to.Length > 1))
msg.To.Add(to);
foreach (var cc in emailCc.Where(cc => cc.Length > 1))
msg.CC.Add(cc);
foreach (var bcc in emailBcc.Where(bcc => bcc.Length > 1))
msg.Bcc.Add(bcc);
//
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(Convert.ToString(email["BODY_TEXT"]), Encoding.UTF8, "text/plain"));
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(Convert.ToString(email["BODY_HTML"]), Encoding.UTF8, "text/html"));
//
new SmtpClient
{
Credentials = new NetworkCredential(_emailUsername, _emailPassword),
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = true,
Host = "smtp.gmail.com"
}.Send(msg);
}
catch (Exception e)
{
L.Get().Fatal("Failed", e);
}
}
Could it be that you're setting the body before you set it to Html?
Worth trying using the full object constructor (new MailMessage(){ IsBodyHtml = true, Body = myString}) or setting the properties one at a time to make sure...
Related
I am sending emails from a C# method, where from one moment to another it stops working and I allow access to my host.
I have not uploaded changes to production, for a long time and I have even less touched this part of the code. I get the following error but I don't know what it means and what solution to give about it:
Error: IoException:
Handshake failed due to unexpected packet format
Code:
string mailFrom = emailSettings.Correo;
string nameFrom = emailSettings.Nombre;
string passwordFrom = emailSettings.Password;
string hostSMTP = emailSettings.HostSMTP;
// Message data
MailAddress fromAddress = new MailAddress(mailFrom, nameFrom, Encoding.UTF8);
MailAddress toAddress = new MailAddress(mailDestino, nombreDestinatario, Encoding.UTF8);
// Specify the message content.
using (MailMessage message = new MailMessage(fromAddress, toAddress)
{
Subject = asuntoMensaje,
SubjectEncoding = Encoding.UTF8,
IsBodyHtml = true,
Body = cuerpoMensaje,
BodyEncoding = Encoding.UTF8,
Priority = MailPriority.Normal,
})
{
// SMTP Cliente
SmtpClient smtp = new SmtpClient
{
Host = hostSMTP,
Port = 587,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(mailFrom, passwordFrom),
DeliveryMethod = SmtpDeliveryMethod.Network,
Timeout = 2 * 60 * 1000 //2 minutos
};
message.Headers.Add("Disposition-Notification-To", mailFrom);
message.Headers.Add("Return-Receipt-To", mailFrom);
// Send the E-Mail
smtp.Send(message);
}
Thank you very much, I look forward to your response.
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.
I've got this code that sends an email with attachment[s]:
internal static bool EmailGeneratedReport(List<string> recipients)
{
bool success = true;
try
{
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
Recipients _recipients = mailItem.Recipients;
foreach (string recip in recipients)
{
Recipient outlookRecipient = _recipients.Add(recip);
outlookRecipient.Type = (int)OlMailRecipientType.olTo;
outlookRecipient.Resolve();
}
mailItem.Subject = String.Format("Platypus Reports generated {0}", GetYYYYMMDDHHMM());
List<String> htmlBody = new List<string>
{
"<html><body><img src=\"http://www.platypus.com/wp-content/themes/duckbill/images/pa_logo_notag.png\" alt=\"Pro*Act logo\" ><p>Your Platypus reports are attached.</p>"
};
htmlBody.Add("</body></html>");
mailItem.HTMLBody = string.Join(Environment.NewLine, htmlBody.ToArray());
. . . // un-Outlook-specific code elided for brevity
FileInfo[] rptsToEmail = GetLastReportsGenerated(uniqueFolder);
foreach (var file in rptsToEmail)
{
String fullFilename = Path.Combine(uniqueFolder, file.Name);
if (!File.Exists(fullFilename)) continue;
if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
{
mailItem.Attachments.Add(fullFilename);
}
MarkFileAsSent(fullFilename);
}
mailItem.Importance = OlImportance.olImportanceHigh;
mailItem.Display(false);
}
catch (System.Exception ex)
{
String exDetail = String.Format(ExceptionFormatString, ex.Message,
Environment.NewLine, ex.Source, ex.StackTrace, ex.InnerException);
MessageBox.Show(exDetail);
success = false;
}
return success;
}
However, it pops up the email window when ready, which the user must respond to by either sending or canceling. As this is in an app that sends email based on a timer generating reports to be sent, I can't rely on a human being present to hit the "Send" button.
Can Outlook email be sent "silently"? If so, how?
I can send email silently with gmail:
private void EmailMessage(string msg)
{
string FROM_EMAIL = "sharedhearts#gmail.com";
string TO_EMAIL = "cshannon#platypus.com";
string FROM_EMAIL_NAME = "B. Clay Shannon";
string TO_EMAIL_NAME = "Clay Shannon";
string GMAIL_PASSWORD = "theRainNSpainFallsMainlyOnDonQuixotesHelmet";
var fromAddress = new MailAddress(FROM_EMAIL, FROM_EMAIL_NAME);
var toAddress = new MailAddress(TO_EMAIL, TO_EMAIL_NAME);
string fromPassword = GMAIL_PASSWORD;
string subject = string.Format("Log msg from ReportScheduler app sent
{0}", DateTime.Now.ToLongDateString());
string body = msg;
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);
}
}
...but when I do that, I have to supply my gmail password, and I don't really want to do that (expose my password in the source code).
So, how can I gain the benefits of gmailing (silence) and Outlook (keeping my password private)?
If you want the shortest way:
System.Web.Mail.SmtpMail.SmtpServer="SMTP Host Address";
System.Web.Mail.SmtpMail.Send("from","To","Subject","MessageText");
This was code that I was reusing from another project where I wanted the send dialog to display, and for the email only to be sent when the user hit the "Send" button. For that reason, it didn't call "send"
To get the email to send silently/unattended, I just needed to add a call to "mailItem.Send()" like so:
mailItem.Importance = OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Send(); // This was missing
My method sends an email using a SMTP Relay Server.
Everything works fine (the email gets sent), except for that the attached file (the image) is somehow compressed/notexistent and not able to retrieve from the email.
The method looks like this:
public static bool SendEmail(HttpPostedFileBase uploadedImage)
{
try
{
var message = new MailMessage() //To/From address
{
Subject = "This is subject."
Body = "This is text."
};
if (uploadedImage != null && uploadedImage.ContentLength > 0)
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(uploadedImage.InputStream, uploadedImage.FileName);
message.Attachments.Add(attachment);
}
message.IsBodyHtml = true;
var smtpClient = new SmtpClient();
//SMTP Credentials
smtpClient.Send(message);
return true;
}
catch (Exception ex)
{
//Logg exception
return false;
}
}
The uploadedImage is not null.
ContentLength is 1038946 bytes (correct size).
However, the email that is being sent contains the image as an attachment with correct filename, although it's size is 0 bytes.
What am I missing?
The second parameter of constructor of System.Net.Mail.Attachment is not the file name. It's the content type.
And perhaps ensure your stream position is 0 before to create attachment
#ChrisRun,
You should change the parameter HttpPostedFileBase as byte[] for example. This way you could re-use your class in more places.
Try changing FileName for ContentType and add the MediaTypeNames.Image.Jpeg.
Also, add the using directive for dispose the MailMessage and SmtpClient
using (var message = new MailMessage
{
From = new MailAddress("from#gmail.com"),
Subject = "This is subject.",
Body = "This is text.",
IsBodyHtml = true,
To = { "to#someDomain.com" }
})
{
if (imageFile != null && imageFile.ContentLength > 0)
{
message.Attachments.Add(new Attachment(imageFile.InputStream, imageFile.ContentType, MediaTypeNames.Image.Jpeg));
}
using (var client = new SmtpClient("smtp.gmail.com")
{
Credentials = new System.Net.NetworkCredential("user", "password"),
EnableSsl = true
})
{
client.Send(message);
}
}
Cheers
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);