Remote Server returned '550 5.6.2 SMTPSEND.BareLinefeedsAreIllegal; message contains bare linefeeds, which cannot be sent via DATA'
var message = new MimeMessage();
message.From.Add(new MailboxAddress(nameFrom, mailboxFrom));
message.Subject = Subject;
message.To.Add(new MailboxAddress(mailboxTo));
var bodyBuilder = new BodyBuilder();
var multipart = new Multipart("mixed");
bodyBuilder.HtmlBody = "Test Body";
multipart.Add(bodyBuilder.ToMessageBody());
byte[] bytes = System.IO.File.ReadAllBytes("Test.gif");
var attachment = new MimePart("binary", "bin")
{
ContentObject = new ContentObject(new MemoryStream(bytes), ContentEncoding.Base64),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Binary,
FileName = "F2.pdf"
};
multipart.Add(attachment);
message.Body = multipart;
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(ssServer, ssPort, MailKit.Security.SecureSocketOptions.Auto);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate(ssMailBox, ssMailBoxPassword);
client.Send(message);
}
I have already tried with encoding ContentEncoding.Base64 and ContentEncoding.Binary with same result. When I skip the attachment part the mail is sent correctly. The "Test.gif" is just a random gif I'm uploading.
I have read about CHUNKING or the BDAT command but not really sure about this or how to use it with mailkit ... any suggestions? I'm just trying to send a normal SMTP mail with attachments, this can't be that hard :|
The solution was, as suggested by #Jstedfast to change:
ContentTransferEncoding = ContentEncoding.Base64
I misunderstood and tried changing the ContentObject enconding.
Thanks #Jstedfast
Related
I am using SmtpClient to send email with attachment.
Can I delete the sent email from sent folder using SmtpClient ?
Here is my code:
ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
using var mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress(s));
mailMessage.From = new MailAddress("mohammad.jouhari#gmail.com");
mailMessage.Subject = "Remote Freelance Web Developer,Mohammad Jouhari Latest CV";
mailMessage.Body = "Dear Hiring Manager,\r\n\r\n Please find attached CV.\r\n\r\n " +
"My work sample:https://github.com/mohammadjouhari.\r\n\r\n" +
"My linkedin Profile: https://www.linkedin.com/in/mohammad-jouhari-42461330/";
string pdfFilePath = "C:\\Users\\m_243\\OneDrive\\Desktop\\microsoft documentation\\.net core\\SendEmailTest" +
"\\SendEmailTest\\wwwroot\\MohammadJouhariCV.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);
var attachment = new Attachment(new MemoryStream(bytes), "MohammadJouhariCV.PDF");
mailMessage.Attachments.Add(attachment);
NetworkCredential loginInfo = new NetworkCredential("mohammad.jouhari#gmail.com", ""); // password for connection smtp if you don't have have then pass blank
SmtpClient _smtpClient = new SmtpClient();
_smtpClient.Host = "smtp.gmail.com";
_smtpClient.Port = 587;
_smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
_smtpClient.EnableSsl = true;
_smtpClient.UseDefaultCredentials = false;
_smtpClient.Credentials = loginInfo;
_smtpClient.Send(mailMessage); // _smtpClient will be disposed by container
_smtpClient.Dispose();
I was trying this code
Pop3Client pop3 = new Pop3Client();
pop3.Host = "smtp.gmail.com";
pop3.Username = "mohammad.jouhari#gmail.com";
pop3.Password = "";
pop3.Port = 587;
pop3.EnableSsl = true;
pop3.Connect();
pop3.DeleteAllMessages();
pop3.Dispose();
I am getting an error in pop3.Connect();
Cannot determine the frame size or a corrupted frame was received
No. The POP3 DELE command deletes from the inbox, not the outbox. Deleting emails from other mailboxes is done through a platform-specific api - the way to do this in Gmail will be different to Outlook. For example, Microsoft uses their Graph api to manage mailboxes. Google calls them 'labels' instead of 'mailboxes' and an email can have more than one label associated with it
I am trying to use the code snippet below. The goal is to just send an email, however I am getting an error "The SMTP server requires a secure connection or the client was not authenticated.".
My question is. What is the best way to send emails via code if an SMPT server requires an authenticated account? Is it bad practice to have a developer type account created for this purpose?
string server = "";
string to = "";
string from = "";
MailMessage message = new MailMessage(from, to);
message. Subject = "Subject";
message. Body = "Body";
SmtpClient client = new SmtpClient(server);
client.UseDefaultCredentials = true;
client. Port = 000;
client.EnableSsl = true;
This is how I send email using System.Net.Mail through office365 smtp.
Yes, you need to have an account and password with office365 to be able to send email through their smtp server. Use the code below, it is the same one I use in my web app to send email to users.
using (var message = new MailMessage())
{
message.To.Add(new MailAddress("recepient email", "receipient name"));
message.From = new MailAddress("your email", "your name");
message.Subject = "My subject";
message.Body = "My message";
message.IsBodyHtml = false; // change to true if body msg is in html
using (var client = new SmtpClient("smtp.office365.com"))
{
client.UseDefaultCredentials = false;
client.Port = 587;
client.Credentials = new NetworkCredential("your email", "your password");
client.EnableSsl = true;
try
{
await client.SendMailAsync(message); // Email sent
}
catch (Exception e)
{
// Email not sent, log exception
}
}
}
I am trying to send email using C# but I am getting below error.
Mailbox was unavailable. The server response was: Relay access denied. Please authenticate.
I am not sure why I am getting this error. Here, I am using smtp2go third party to send this email.
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#wraptite.com");
mail.To.Add("test1#gmail.com");
mail.Subject = "Test Email";
mail.Body = "Report";
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
//SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
I've tried your code and it work fine.
But in my case, to use the smtp server, from(email address of sender) must use the same domain to authenticate.(but gmail is available to this Send emails from a different address or alias)
So, If your SMTP server connect to smtp2go.com, try as below.
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#smtp2go.com");
Or if you need to use service of smtp2go, it would be better use rest API.
Here is updated by your comment when using gmail.
Gmail required secure app access. that's a reason why code is not work.
So, there is two options for this.
1. Update your gmail account security
(origin idea from here : C# - 이메일 발송방법)
Go to here and turn on "Less secure app access". after doing this your code will work.(it works)
2. Using "Google API Client Library for .NET."
I think this is not so easy, check this out, I found an answer related with this here
#region SendMail
//Mail Setting
string EmailSubject = "EmailSubject";
string EmailBody = "EmailBody";
try
{
string FromAddress = "abc#gmail.com";
string EmailList = "abc1#gmail.com";
string EmailServer = "ipofemailserver";
using (var theMessage = new MailMessage(FromAddress, EmailList))
{
// Construct the alternate body as HTML.
string body = "EmailBody";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
theMessage.AlternateViews.Add(alternate);
theMessage.Subject = EmailSubject;
theMessage.IsBodyHtml = true;
SmtpClient theSmtpServer = new SmtpClient();
theSmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
theSmtpServer.Host = EmailServer;
theSmtpServer.Send(theMessage);
}
}
catch (Exception ex)
{
string AppPath = AppDomain.CurrentDomain.BaseDirectory;
string ErrorPath = AppDomain.CurrentDomain.BaseDirectory + "File\\Error\\";
string OutFileTime = DateTime.Now.ToString("yyyyMMdd");
using (StreamWriter sw = new StreamWriter(ErrorPath + OutFileTime + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(ex.ToString());
sw.Close();
}
}
#endregion
I have an API which gives me path to a file http://bts.myurl.com/ThisIsMyPdf.pdf.
Now I have a button which onto clicking share this file to users via mail. This is the code which i have used for sending the report:
var filePath = "http://bts.myurl.com/ThisIsMyPdf.pdf";
Utilities.SendEmail("MyId#gmail.com", "subject", "To#gmail.com", "", "", "body", filePath);
But this is giving exception as URI Formats are not supported.
Some other approaches include the file to be download first before sending as attachment but again i don't want it to be downloaded.
I believe there are other ways to achieve this, if any please share.
As suggested by #dlatikay, hereby sharing a working code for the above problem.
//This is the code get byte stream from the URL
WebClient myClient = new WebClient();
byte[] bytes = myClient.DownloadData("http://www.examle.com/mypdf.pdf");
System.IO.MemoryStream webPdf = new MemoryStream(bytes);
//To Create the Attachment for sending mail.
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
Attachment attach = new Attachment(webPdf, ct);
attach.ContentDisposition.FileName = "myFile.pdf";
var smtp = new SmtpClient
{
Host = "email.domainName.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
})
{
//Here webpdf is the bytestream which is going to attach in the mail
message.Attachments.Add(new Attachment(webPdf, "sample.pdf"));
smtp.Send(message);
}
webPdf.Dispose();
webPdf.Close();
I have been roaming forums and not finding any answer to my question.
all of the solution (and question) is about using Microsoft.Office.Interop.Outlook;
for some reason I am not allowed to use any office.interop.
I even tried:
MailAddress fromAddress = new MailAddress("sender#server.com");
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = fromAddress;
message.To.Add("receiver#theirServer.com");
message.CC.Add("receiver2#theirServer.com");
message.Subject = "theSubject";
message.Body = "TheBody";
SmtpClient smtpClient = new SmtpClient("zzz.server.xxx");
smtpClient.Credentials = new NetworkCredential("sender#server.com", "password");
smtpClient.Send(message);
the code fail to authenticate the credential, even after I hard-coded the password, but I feel that there must be a better way.
There is a lot to be desired of your question. Can you post the response from the server or the error you are receiving?
Here are some observations and feedback that may help you
Specify the port
SmtpClient smtpClient = new SmtpClient("zzz.server.xxx", PORTNUMBER);
Set some of the basic properties
smtpClient.Timeout = 10000;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false; //must be set prior to credentials
smtpClient.Credentials = new NetworkCredential("username", "pass");
Set the message encoding
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.BodyEncoding = System.Text.Encoding.UTF8;
Send Asyncronously and use a callback to determine the result
//add callback
smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
//set token
string userToken = "tokenString";
//send asynchronously
smtpCient.SendAsync(message, userToken);
public static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string) e.UserState;
if (e.Cancelled)
{
//do something if it was cancelled
}
if (e.Error != null)
{
MessageBox.Show( e.Error.ToString());
} else
{
MessageBox.Show("Message sent.");
}
}
Have you verified the credentials, including the format of the username through configuring the account in an alternative client, such as Outlook?
You might need:
smtpClient.Credentials = new NetworkCredential("sender", "password");
or
smtpClient.Credentials = new NetworkCredential("DOMAIN\sender", "password");
Is your email server an Exchange Server? If so, you can use the Exchange Web Services (EWS) to send emails and save copies in the Sent Items folder. A simple example can be seen here:
Send Exchange Email
More Sample Code