How do I rename file before sending - c#

I am using Mailkit with c# to send an email with an attachment.
How do I rename the attachment before sending the email?
I am currently using the code below but throws an error when deployed in IIS.
var username = "username";
var password = "password";
var displayname = "display";
var from = new MailboxAddress(displayname, username);
var to = new MailboxAddress("User", emailto);
msg.From.Add(from);
msg.To.Add(to);
msg.Subject = emailsubject;
var attachment = new MimePart("application","zip")
{
Content = new MimeContent(File.OpenRead(Path.Combine(fileutil.GetDir, "originalname.zip"))),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = "new filename.zip"
};
var msgbody = new BodyBuilder
{
HtmlBody = string.Format(#"Message"),
TextBody = "Test Message!"
};
msgbody.Attachments.Add(attachment);
msg.Body = msgbody.ToMessageBody();
var client = new SmtpClient();
client.Connect("smtp-mail.outlook.com", 587, SecureSocketOptions.StartTls);
client.Authenticate(username, password);
client.Send(msg);
client.Disconnect(true);
client.Dispose();
Edit: After a bit of digging, I found out that this is the exception thrown
The server's SSL certificate could not be validated for the following reasons:
• The server certificate has the following errors:
• The revocation function was unable to check revocation for the certificate.
• The revocation function was unable to check revocation because the revocation server was offline.
• An intermediate certificate has the following errors:
• The revocation function was unable to check revocation for the certificate.
• The revocation function was unable to check revocation because the revocation server was offline.```

Try this:
var client = new SmtpClient();
client.ServerCertificateValidationCallback = (o, c, ch, e) => true;
client.Connect("smtp-mail.outlook.com", 587, SecureSocketOptions.StartTls);
client.Authenticate(username, password);

Related

C# SmtpException - problem with sending mails

Sending mails doesn't work. I'm not sure if it's something with client settings or mail server...
When using Gmail SMTP server I got "Connection closed" exception, when changing port to 587 I get "Authentication required" message. What's more interesting when changing SMTP server to something different (smtp.poczta.onet.pl) I get "Time out" exception after ~100s
Here's the code:
protected void SendMessage(object sender, EventArgs e)
{
// receiver address
string to = "******#student.uj.edu.pl";
// mail (sender) address
string from = "******#gmail.com";
// SMTP server address
string server = "smtp.gmail.com";
// mail password
string password = "************";
MailMessage message = new MailMessage(from, to);
// message title
message.Subject = TextBox1.Text;
// message body
message.Body = TextBox3.Text + " otrzymane " + DateTime.Now.ToString() + " od: " + TextBox2.Text;
SmtpClient client = new SmtpClient(server, 587);
client.Credentials = new System.Net.NetworkCredential(from, password);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
try
{
client.Send(message);
// ui confirmation
TextBox3.Text = "Wysłano wiadmość!";
// disable button
Button1.Enabled = false;
}
catch (Exception ex)
{
// error message
TextBox3.Text = "Problem z wysłaniem wiadomości (" + ex.ToString() + ")";
}
}
I've just read that google don't support some less secure apps (3rd party apps to sign in to Google Account using username and password only) since 30/05/22. Unfortunately can't change it because I have two-stage verification account. Might it be connected? Or is it something with my code?
Gmail doesn't allow, or want you to do that with passwords anymore. They ask you to create a credentials files and then use a token.json to send email.
Using their API from Google.Apis.Gmail.v1 - from Nuget. Here is a method I made and test that is working with gmail.
void Main()
{
UserCredential credential;
using (var stream =
new FileStream(#"C:\credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels = request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
//Console.Read();
var msg = new Google.Apis.Gmail.v1.Data.Message();
MimeMessage message = new MimeMessage();
message.To.Add(new MailboxAddress("", "toemail.com"));
message.From.Add(new MailboxAddress("Some Name", "YourGmailGoesHere#gmail.com"));
message.Subject = "Test email with Mime Message";
message.Body = new TextPart("html") {Text = "<h1>This</h1> is a body..."};
var ms = new MemoryStream();
message.WriteTo(ms);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string rawString = sr.ReadToEnd();
byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
msg.Raw = System.Convert.ToBase64String(raw);
var res = service.Users.Messages.Send(msg, "me").Execute();
res.Dump();
}
static string[] Scopes = { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels, GmailService.Scope.GmailCompose, GmailService.Scope.MailGoogleCom};
static string ApplicationName = "Gmail API Send Email";
Enable 2FA on your email and generate a password for your application using the link. As far as I know, login and password authorization using unauthorized developer programs is no longer supported by Google.
Can you ping the smpt server from your machine or the machine you deploy the code from? THis could be a DNS issue.

SMTP Send E-Mail Office 365 MustIssueStartTlsFirst

Im trying to send an email with the office 365 smtp, but im getting the following error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57
Client not authenticated to send mail. Error: 535 5.7.139
Authentication unsuccessful, the user credentials were incorrect.
[XXXX.XXXX.prod.outlook.com]
I noticed that some things got changed "recently" with the office 365 smtp and the most recent code, that I found, that works for most people was this:
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Host = "smtp.office365.com";
mySmtpClient.Port = 587;
mySmtpClient.UseDefaultCredentials = false;
mySmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mySmtpClient.Credentials = new NetworkCredential(email, password);
mySmtpClient.TargetName = "STARTTLS/smtp.office365.com";
mySmtpClient.EnableSsl = true;
// add from,to mailaddresses
MailAddress from = new MailAddress(email);
MailAddress to = new MailAddress(email);
MailMessage myMail = new System.Net.Mail.MailMessage(from, to);
// set subject and encoding
myMail.Subject = "Test message";
myMail.SubjectEncoding = System.Text.Encoding.UTF8;
// set body-message and encoding
myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
myMail.BodyEncoding = System.Text.Encoding.UTF8;
// text or html
myMail.IsBodyHtml = true;
mySmtpClient.Send(myMail);
But Im still getting the same error as before (MustIssueStartTlsFirst).
Anyone know the problem?

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Office 365 error

Trying to send an email via MVC 5 C#. This newly created email address is on an office 365 server. Tried numerous solutions online but to no avail I get the following error message: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [LO3P265CA0018.GBRP265.PROD.OUTLOOK.COM]'. My code is as follows:
public void ConcernConfirmEmail(Appointments a, EmailConfig ec)
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
tokens.Add("Name", a.sirenDetail.FirstName);
tokens.Add("Time", a.start.ToString("HH:mm"));
tokens.Add("Date", a.start.ToString("dd/MM/yyyy"));
tokens.Add("Location", a.site.SiteDescription);
using (SmtpClient client = new SmtpClient()
{
Host = "smtp.office365.com",
Port = 587,
UseDefaultCredentials = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(ec.EmailUser, ec.EmailPassword),
TargetName = "STARTTLS/smtp.office365.com",
EnableSsl = true
})
{
MailMessage message = new MailMessage()
{
From = new MailAddress("emailadress#myorg.net"),
Subject = "Subject",
Sender = new MailAddress("emailadress214#myorg.net", "password"),
Body = PopulateTemplate(tokens, GetTemplate("ConfirmTemplate.html")),
IsBodyHtml = true,
BodyEncoding = System.Text.Encoding.UTF8,
SubjectEncoding = System.Text.Encoding.UTF8,
};
message.To.Add(a.sirenDetail.EmailAddress.ToString());
client.Send(message);
}
}
According to oficcial microsoft documentation, SmtpClass is obsolete for a while now, microsoft encourages deveopers to use new open souce Smtp implementations, like MailKit.
When using MailKit with username and password authentication, you have to set the authentication mechanism to use NTLM.
Here is a working example:
public async Task Send(string emailTo, string subject, MimeMessage mimeMessage, MessagePriority messagePriority = MessagePriority.Urgent)
{
MimeMessage mailMessage = mimeMessage;
mailMessage.Subject = subject;
mailMessage.Priority = messagePriority;
if (emailTo.Contains(';'))
{
foreach (var address in emailTo.Split(';'))
{
mailMessage.To.Add(new MailboxAddress("", address));
}
}
else
{
mailMessage.To.Add(new MailboxAddress("", emailTo));
}
mailMessage.From.Add(new MailboxAddress("Sender", _smtpCredentials.SenderAddress));
using var smtpClient = new SmtpClient
{
SslProtocols = SslProtocols.Tls,
CheckCertificateRevocation = false,
ServerCertificateValidationCallback = (s, c, h, e) => true,
};
await smtpClient.ConnectAsync(_smtpCredentials.Server, _smtpCredentials.Port, SecureSocketOptions.StartTlsWhenAvailable);
await smtpClient.AuthenticateAsync(new SaslMechanismNtlm(new NetworkCredential(_smtpCredentials.User, _smtpCredentials.Password)));
try
{
await smtpClient.SendAsync(mailMessage);
}
catch (Exception ex)
{
}
finally
{
if (smtpClient.IsConnected) await smtpClient.DisconnectAsync(true);
}
}
The most important line here is
await smtpClient.AuthenticateAsync(new SaslMechanismNtlm(new NetworkCredential(_smtpCredentials.User, _smtpCredentials.Password)));
That is setting the NTLM as the authentication mechanism for the client to use.
But
If you are unable to change Smtp library right now, you can try change your code to look like this, as imcurrent using in older services and work fine:
using (var smtpClient = new SmtpClient(smtpServer)
{
UseDefaultCredentials = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(user, password),
EnableSsl = false,
Port = 587
})
See that the change is on just on the EnableSsl set to false, and not needded to set the TargetName property.
Hope this helps

SMTP gmail on windows application

I have a problem trying to send email (gmail) it won't allow me to send email if I didn't have the 'allow less secure app' turned on. What am I doin wrong?
try
{
smtpClient.Host = mServer;
smtpClient.Port = mPort;
smtpClient.EnableSsl = isenableSsl;
//Input new time out
if (mTimeout > 0)
{
smtpClient.Timeout = mTimeout;
}
//Check Authentication Mode
if (isAuthentication)
{
//Create Network Credentail if SMTP Server Turn On Authentication Mode
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = mUserName;
credentials.Password = mPassword;
smtpClient.Credentials = credentials;
smtpClient.UseDefaultCredentials = false;
}
else
{
smtpClient.UseDefaultCredentials = true;
}
//Configuration Mail Information
if (string.IsNullOrEmpty(mDisplay)) mailMessage.From = new MailAddress(mFrom);
else mailMessage.From = new MailAddress(mFrom, mDisplay);
mailMessage.Sender = new MailAddress(mFrom);
mailMessage.ReplyTo = new MailAddress(mFrom);
//Set To Email Information
if (ToEmails.Count != 0)
{
mailMessage.To.Clear();
foreach (string mail in ToEmails)
{
mailMessage.To.Add(mail);
}
}
//Set Cc Email Information
mailMessage.CC.Clear();
foreach (string mail in CcEmails)
{
mailMessage.CC.Add(mail);
}
//Set Bcc Email Information
mailMessage.Bcc.Clear();
foreach (string mail in BccEmails)
{
mailMessage.Bcc.Add(mail);
}
//Set Mail Information
mailMessage.Subject = mSubject;
mailMessage.Body = mBody;
//Configuration Mail Option
mailMessage.IsBodyHtml = isBodyHtml;
mailMessage.SubjectEncoding = mSubjectEncoding;
mailMessage.BodyEncoding = mBodyEncoding;
mailMessage.Priority = mPriority;
mailMessage.DeliveryNotificationOptions = mDeliveryNotificationOptions;
//Clear Attachment File
mailMessage.Attachments.Clear();
//Add Attachments Internal File
AddAttachImage(ref mailMessage);
//Add Attachments External File
if (attachmentFiles.Count > 0)
{
AddAttachFile(ref mailMessage);
}
//Link Event Handler
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
//Send Message Fuction
SetLogfileSendEmail(smtpClient, mailMessage);
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{ return true; };
smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
strInformation.Append("(Error) Method smtpClient_SendCompleted : " + ex.Message);
WriteLogFile();
throw new Exception("SMTP Exception: " + ex.Message);
}
}
It is also giving me this
SMTP Exception: The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.7.0 Authentication Required.
I want to be able to send email without having to turn on the "allow less secure app" option on gmail account.
Is there any other way for third party apps to send emails without having to do 'allow less secure apps' ??
If you (sender) use gmail provider, try to activate this option
https://www.google.com/settings/security/lesssecureapps

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP

I know that this an old question but I can find a solution for my problem, here is the thing , I am trying to send a email via smtp of outlook , but I get this error message: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP, sorry for my english.
public void Send(MailMessage message)
{
msgToSend = message;
string password = string.Empty;
password = CryptoHelper.DecryptData("encoded_password", "key");
var smtpClient = new SmtpClient("smtp.office365.com", 587);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("username", "password");
smtpClient.EnableSsl = true;
smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
smtpClient.SendCompleted += (s, e) =>
{
smtpClient.Dispose();
message.Dispose();
};
smtpClient.SendAsync(message, null);
}

Categories

Resources