Email attachement using uri via smptclient and C# - c#

i have to do the following: my documents are stored on a server. The only path i'm getting is an URI
I was trying to get the document but i'm keep getting a "403 Forbidden".
string[] myArray = context.Request.QueryString["ItemsArray"].Split(',');
MailMessage m = new MailMessage(new MailAddress("bart#schelkens.be"),
new MailAddress("bart#schelkens.be")
);
m.Subject = "Emailing documents";
foreach (string path in myArray)
{
using (WebClient wb = new WebClient())
{
wb.UseDefaultCredentials = false;
wb.Credentials = new NetworkCredential(_userName, _passWord);
var stream = wb.OpenRead(path);
m.Attachments.Add(new Attachment(stream, ""));
}
}
string mailBody = "Dear<BR/> Please find attached a new version of the documents.";
mailBody += "<BR/>";
m.Body = mailBody;
m.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("hybrid.kaneka.be");
smtp.EnableSsl = false;
smtp.Send(m);
Or is there another way to get my document from the website and then mail it?
In SharePoint I created my own button which, using a js-file, goes to my ashx to mail my documents.

Try to add the following line before opening the stream:
wb.Headers.Add("User-Agent: Other");
It could be, that it's forbidden because your server doesn't think, that you are a trusted client and blocks all connections without a User-Agent.
[edit 1]
If you try to download a file from SharePoint you have to use the SharePointOnlineCredentials from the SharePoint Server 2013 Client Components SDK:
Somewhere you have to define the credentials:
const string username = "username";
const string password = "password";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);
After that you can user this credentials in your WebClient:
wb.Credentials = credentials;
[edit 2]
If your on in an on-premises environment than you could use NetworkCredentials. Try to use the following:
wb.Credentials = new NetworkCredential("DOMAINNAME\username", "password");
[edit 3]
Maybe your server wants a real User-Agent. Because if something is wrong with your credentials there would be a 401 (unauthorized). For example try:
wb.Headers.Add("user-agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");

Provide the READ/WRITE rights/permission on the folder where your document is located.
Currently there is no read/write rights/permission on that folder that's why when ever you try to attach the document it returns 403 Forbidden error.

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.

How do I rename file before sending

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);

Basic authentication requires a secure connection to the server. in TFS

I was try to connect my TFS server using my credentials . But i am getting error 'Basic authentication requires a secure connection to the server.'
string username = "adminuser";
string pwd = "mypassword";
string domain = "http://localhost:8080/tfs/defaultcollection";
NetworkCredential networkCredential = new NetworkCredential(username, pwd);
BasicAuthCredential basicAuthCredential = new BasicAuthCredential(networkCredential);
TfsClientCredentials tfsClientCredentials = new TfsClientCredentials(basicAuthCredential)
{
AllowInteractive = false
};
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(domain), tfsClientCredentials);
tfs.EnsureAuthenticated();
My tfs didn't have the https. Any alternative to fix it But browser level it is working fine
The BasicAuthCredential requires https://, I believe, and I wasn't able to access my TFS with https://. So I found another way to get from NetworkCredential to VssCredentials.
string username = "adminuser";
string pwd = "mypassword";
string domain = "http://localhost:8080/tfs/defaultcollection";
NetworkCredential networkCredential = new NetworkCredential(username, pwd);
//BasicAuthCredential basicAuthCredential = new BasicAuthCredential(networkCredential);
Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(networkCredential);
VssCredentials vssCred = new VssClientCredentials(winCred);
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(domain), vssCred);
tfs.EnsureAuthenticated();
Try using the following code:
String collectionUri = "http://localhost:8080/tfs/defaultcollection";
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
VssConnection connection = new VssConnection(new Uri(collectionUri), creds);

Sending Email in ASP.NET without Logging in

In my search for a way to send email on my webapp through a form, the only solution I got working was an old MSDN solution for a WebMail helper where it had me hardcode the credentials for an email to send through.
Right, off the bat, I know this is not ideal. Is there an easy way to send this mail out from a WebMail default so I can remove the login credentials and not look so amateurish???
#{
var customerName = Request["customerName"];
var customerEmail = Request["customerEmail"];
var customerPhone = Request["customerPhone"];
var customerRequest = Request["customerRequest"];
var errorMessage = "";
var toMail = "user#mail.com";
var debuggingFlag = false;
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.SmtpPort = 587;
WebMail.UserName = "user#mail.com";
WebMail.Password = "Password!";
WebMail.From = "user#mail.com";
WebMail.EnableSsl = true;
// Send email
WebMail.Send(to: toMail,
subject: "Quote/Info request from - " + customerName,
body: customerPhone + customerRequest
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
See the mailSettings element of you web.config file.
For some reason the msdn page on the WebMail class recommends the _AppStart.cshtml file as a suitable place to configure these settings.

How can I send emails from my SMTP server?

Hello I have a hosted Windows Server 2008 R2 Enterprise and a purchased domain name. I have pointed everything on my domain to my server's dns and uploaded my ASP.Net site to the IIS. I have also set up an SMTP Feature so now I'm trying to send emails from my SMTP but I can't because the application says that the user is not authenticated.
Here is the source code of my page:
MailMessage activationMail = new MailMessage();
activationMail.From = new MailAddress("no-reply#mydomain.com", "MyGame");
activationMail.To.Add(RegistrationEmail.Text);
StreamReader sRead = new StreamReader(Server.MapPath("~/Mails/ActivationMail.html"));
string readFile = sRead.ReadToEnd();
string Strcontent = "";
Strcontent = readFile;
Strcontent = Strcontent.Replace("[Name]", RegistrationRealName.Text);
Strcontent = Strcontent.Replace("[Username]", RegistrationUsername.Text);
Strcontent = Strcontent.Replace("[Password]", RegistrationPasswordCreate.Text);
Strcontent = Strcontent.Replace("[useractivation]", useractivation);
Strcontent = Strcontent.Replace("[Site]", site);
Strcontent = Strcontent.Replace("[Facebook]", "facebook");
activationMail.Subject = "My Game - Registration";
activationMail.Body = Strcontent.ToString();
sRead.Close();
activationMail.IsBodyHtml = true;
activationMail.BodyEncoding = UTF8Encoding.UTF8;
SmtpClient client = new SmtpClient();
client.Host = "mydomain";
NetworkCredential cr = new NetworkCredential();
cr.UserName = "User from AD DS";
cr.Password = "Password of User";
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Port = 25;
client.Timeout = 10000;
client.Send(activationMail);
Note: My domain name is not the same with my forest's domain. I have also tried to set my forest's domain as the client.Host but same result. I have these settings on my Web.config
<mailSettings>
<smtp from="no-reply#mydomain">
<network defaultCredentials="false" host="localhost" />
</smtp>
</mailSettings>
My SMTP server's settings are these:
IP Address = My server's IP
Authentication = Standar & Windows authentication are checked, TSL is checked, Default domain is set to my domain (not my MX record mail.domain). Anonymous authentication is not checked.
Connection = Only my server's IP has access
Relay = Only my purchased domain (not MX record) has access
Outbound security = Standar authentication (User from AD DS - same credentials with the ones at my cs file above), TLS enabled
Advanced delivery options = I set my domain name there (not MX record - gives me an error)
Does anybody know what am I doing wrong?
Add the following code as you haven't provided any credentials to the smtp:
client.Credentials = cr;
Like:
NetworkCredential cr = new NetworkCredential();
cr.UserName = "User from AD DS";
cr.Password = "Password of User";
client.Credentials = cr;
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Port = 25;
client.Timeout = 10000;
client.Send(activationMail);
try adding these two line:
client.EnableSsl = false;
client.Credentials = cr;

Categories

Resources