I want to get the email's ConversationId after sending an email.
I am using Microsoft exchange web services package for sending an email.
using Microsoft.Exchange.WebServices.Data;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.UseDefaultCredentials = false;
service.Credentials = new WebCredentials('*****', '*****');
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl(emailExist.Email, RedirectionUrlValidationCallback);
EmailMessage emailMessage = new EmailMessage(service);
emailMessage.From = "abcd#xyz.com";
emailMessage.Subject = "testing email";
emailMessage.Body = new MessageBody(BodyType.HTML, "<b>Hello</b> World");
if (!string.IsNullOrEmpty(email.To))
{
var toArr = email.To.Split(',');
foreach (var toAddress in toArr)
{
emailMessage.ToRecipients.Add(toAddress.Trim());
}
}
// Send message and save copy by default to sentItems folder
emailMessage.SendAndSaveCopy();
In EWS Sends are asynchronous so you won't get back the Id of the message you just send in the Send Method. If you save the Message as a draft first before sending it that should populate both the Message and CoversationId's eg
EmailMessage em = new EmailMessage(service);
em.Subject = "Test"
em.Save();
em.Load();
Console.WriteLine(em.ConversationId.UniqueId);
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 to send an email through Exchange. I found that I can do this using ExchangeService. I've tried many ways to do this, but only what I've got is error: (440) Login Timeout.
I don't even know if there is a problem with credentials, or my code is wrong.
string login = #"login";
string password = #"password";
ExchangeService service = new ExangeService();
service.Credentials = new NetworkCredential(login, password);
service.Url = new Uri(#"https://mail.exchangemail.com");
EmailMessage message = new EmailMessage(service);
message.Subject = "Interesting";
message.Body = "The proposition has been considered.";
message.ToRecipients.Add("quarkpol#gmail.com");
message.From = "quarkpol_test#gmail.com";
message.Send();
I've found the problrm solution on the web, and it works.
using EASendMail;
string login = #"login";
string password = #"password";
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
oMail.From = "from#email.com";
oMail.To = "to#email.com";
oMail.AddAttachment(fileName, fileByteArray);
oMail.Subject = "Subject";
oMail.HtmlBody = "HTMLBody";
SmtpServer oServer = new SmtpServer("mail.email.com");
oServer.Protocol = ServerProtocol.ExchangeEWS;
oServer.User = login;
oServer.Password = password;
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
try
{
Console.WriteLine("start to send email ...");
oSmtp.SendMail(oServer, oMail);
Console.WriteLine("email was sent successfully!");
}
catch (Exception ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
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