I am sending emails thorugh c#. The body of the mail is dynamic i.e. user fills it in before sending the mail. Issue is the body text is coming in a single line instead of multiple lines as they should.
using (MailMessage mm = new MailMessage(txtEmail.Text.Trim(), email.Trim()))
{
try
{
mm.CC.Add(txtcc.Text.Trim());
mm.Subject = txtSubject.Text.Trim();
mm.Body = txtBody.Text;
MemoryStream pdf = new MemoryStream(bytes);
mm.Attachments.Add(new Attachment(pdf, "Report.pdf"));
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = txtEmail.Text.Trim();
credentials.Password = txtPassword.Text.Trim();
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}
catch (Exception ex)
{
Alert.show1("Could not send the e-mail - error: " + ex.Message, this);
return;
}
}
If you dont need the potential of HTML formatting, you could avoid the problem changing the email format to plain text. This could also avoid user entering text that could be parsed as html.
mm.IsBodyHtml = false;
Otherwise you should change the end line character to html breaking line:
mm.IsBodyHtml = true;
mm.Body = mm.Body.Replace(#"\n", "<br />");
In case of the html format option, It would be wise to follow Fildor's comment and add an alternateView in plain text for email clients that are not html capable.
Related
I am trying to send email with my office 365 credentials using C#. But It is failing to send and getting exception.
How to fix this? Is it possible to send from office 365?
foreach (var filename in files)
{
String userName = "sri#MyOffice365domain.com";
String password = "password";
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.office365.com");
mail.From = new MailAddress("sri#MyOffice365domain.com");
mail.To.Add("senderaddress#senderdomain.com");
mail.Subject = "Fwd: for " + filename;
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(filename);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(userName, password);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message.
How many emails are you going to send simultaneously?
foreach (var filename in files)
All Outlook APIs accessed via https://outlook.office.com/api or https://outlook.office365.com/api have a limit is 60 requests per minute, per user (or group), per app ID. So, for now, developers only can make limited APIs calls from the app. Read through the Microsoft Blog Post for more details on REST API call limitations.
Try to use the following code instead:
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("someone#somedomain.com", "SomeOne"));
msg.From = new MailAddress("you#yourdomain.com", "You");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("your user name", "your password");
client.Port = 587; // You can use Port 25 if 587 is blocked (mine is!)
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
lblText.Text = "Message Sent Succesfully";
}
catch (Exception ex)
{
lblText.Text = ex.ToString();
}
The richtextbox gets it's value copied from a word file that has an image and text. The code below only sends the text and not the image. How can I get it to send both?
using (MailMessage mm = new MailMessage("xxx#gmail.com","xxxx#gmail.com"))
{
mm.Subject = "demo";
TextRange txc = new TextRange(txt_1.Document.ContentStart, txt_1.Document.ContentEnd);
MemoryStream ms = new MemoryStream();
txc.Save(ms, DataFormats.Xaml);
string xamlText = ASCIIEncoding.Default.GetString(ms.ToArray());
// string sa = ASCIIEncoding.Default.GetBytes(ms.ToArray()).ToString();
mm.Body = xamlText;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("xxxx#gmail.com", "xxxxxx");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
// ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
The problem is that you're taking binary data and explicitly converting it to ASCII text:
string xamlText = ASCIIEncoding.Default.GetString(ms.ToArray());
In so doing, you're altering the original values of the bytes in the image.
You're either going to want to change the BodyEncoding/TransferEncoding of the message Body and encode the data likewise (e.g. Base64 or MIME encoding), or extract the images from the file stream and add them to the mail as attachments. There's a good primer on email encoding here: http://email.about.com/cs/standards/a/mime.htm
Hi I need to send an email using template in c# windows application . I had created a template but i am unable to pass the parameters through the html template. Here is the template which i am using.
For this HTML Template i am calling this in my windows application and sending through gmail smtp. I am able to send the mail but unable to pass the parameters into it. Please Help me out.Here is the code where i am calling in my windows application
try
{
using (StreamReader reader = File.OpenText("H:\\Visitor Management_Project\\Visitor Management_Project\\Visitor Management_Project\\EmailTemplate.htm"))
{
SmtpClient SmtpServer = new SmtpClient("173.194.67.108", 587);
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.Credentials = new System.Net.NetworkCredential("ambarishkesavarapu#gmail.com", "*******");
//SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.EnableSsl = true;
message = new MailMessage();
message.Subject = "Visitor Arrived";
//message.SubjectEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
message.Body = "EmailTemplate.htm";
//message.BodyEncoding = System.Text.Encoding.UTF8;
message.From = new MailAddress("ambarishkesavarapu#gmail.com");
message.To.Add(lblCPEmail.Text);
message.Priority = MailPriority.High;
message.Body = reader.ReadToEnd();
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpServer.Send(message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
How to add Parameters into HTML Template where i am getting all the parameters of that in the same page in Textboxes. Please help me out
I think you already discovered the answer yourself, but I will keep posting the answer instead.
In case you are using Windows Forms and not Windows Presentation Forms (The different only the design part and many new features that does not have on Windows Forms), what I have done is like this (to send email):
public void SendEmail(string _from, string _fromDisplayName, string _to, string _toDisplayName, string _subject, string _body, string _password)
{
try
{
SmtpClient _smtp = new SmtpClient();
MailMessage _message = new MailMessage();
_message.From = new MailAddress(_from, _fromDisplayName); // Your email address and your full name
_message.To.Add(new MailAddress(_to, _toDisplayName)); // The recipient email address and the recipient full name // Cannot be edited
_message.Subject = _subject; // The subject of the email
_message.Body = _body; // The body of the email
_smtp.Port = 587; // Google mail port
_smtp.Host = "smtp.gmail.com"; // Google mail address
_smtp.EnableSsl = true;
_smtp.UseDefaultCredentials = false;
_smtp.Credentials = new NetworkCredential(_from, _password); // Login the gmail using your email address and password
_smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
_smtp.Send(_message);
ShowMessageBox("Your message has been successfully sent.", "Success", 2);
}
catch (Exception ex)
{
ShowMessageBox("Message : " + ex.Message + "\n\nEither your e-mail or password incorrect. (Are you using Gmail account?)", "Error", 1);
}
}
And I am using it like this:
SendEmail(textBox2.Text, textBox5.Text, textBox3.Text, "YOUR_FULL_NAME", textBox4.Text, textBox6.Text, "YOUR_EMAIL_PASSWORD");
Here is the image:
May this answer would help you.
Cheers!
I am trying to send email using c# following is my code.
try
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress("kmrizwan.shahid#gmail.com");
msg.To.Add("kmrizwan.shahid#gmail.com");//Text Box for To Address
msg.Subject = "Testinng subject"; //Text Box for subject
msg.IsBodyHtml = true;
msg.Body = "testing comment is here..";//Text Box for body
msg.Priority = MailPriority.High;
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("kmrizwan.shahid#gmail.com", "");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
object userstate = msg;
client.Send(msg);
}
catch (Exception ex)
{
throw ex;
}
Giving following exception
It's common for internet providers to block the port used by SMTP, except to their own outgoing mailserver. The reason is to prevent spamming.
If that is the case for you, you need to use the mail server of your internet provider instead of the GMail server.
I'm developing a simple send mail app in C#, using my CMail Server:
MailMessage mail = new MailMessage("from#mail.com", "destination#mail.com");
mail.Subject = "Sub";
mail.Body = "Hi!";
SmtpClient smtp = new SmtpClient("MyServer");
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("user", "pass");
smtp.UseDefaultCredentials = false;
smtp.Credentials = cred;
smtp.Send(mail);
Obviously i ommited my account information, so, this code throws me an Authentication Exception for some reason. I first thought that the code was wrong, so i change the info to my gmail account and everything goes fine, with the only SMTP server that i having trouble is with the CMail. Is there a problem with .NET and CMail's SMTP ?
Thanks for the help and comments!
Try adding:
smtp.EnableSsl = true;
If you are using 2-step verification then you will need to add application specific password.
Full work sample
public static void sendEmail()
{
//for use GMAIL require enable -
//https://myaccount.google.com/lesssecureapps?rfn=27&rfnc=1&eid=39511352899709300&et=0&asae=2&pli=1
Console.WriteLine("START MAIL SENDER");
//Авторизация на SMTP сервере
SmtpClient Smtp = new SmtpClient("smtp.gmail.com", 587);
Smtp.EnableSsl = true;
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
Smtp.UseDefaultCredentials = false;
//username password
Smtp.Credentials = new NetworkCredential("rere", "rere");
//Формирование письма
MailMessage Message = new MailMessage();
Message.From = new MailAddress("rere#gmail.com");
Message.To.Add(new MailAddress("rere#gmail.com"));
Message.Subject = "test mesage";
Message.Body = "tttt body";
string file = "D:\\0.txt";
if (file != "")
{
Attachment attach = new Attachment(file, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attach.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
Message.Attachments.Add(attach);
Console.WriteLine("ADD FILE [" + file + "]");
}
try
{
Smtp.Send(Message);
MessageBox.Show("SUCCESS");
}
catch { MessageBox.Show("WRONG"); }
}