what is the diffrence between outlook.office365.com and smtp.office365.com while send email using smtpclient in C#
Earlier our client was used outlook.office365.com
to connect SMTP client and authenticate its working fine now everywhere, but our organization's network firewall not allowed outlook.office365.com
so it's not working on MY LOCAL machine, our network team told me you can use smtp.office365.com
instead of outlook.office365.com
, it's working MY LOCAL And Development environment.
but, I am still confused and to why use smtp.office365.com
instead of outlook.office365.com
and what is the main difference between both of them?
SmtpClient client = new MailKit.Net.Smtp.SmtpClient();
client.Connect("smtp.office365.com", 587, false);
1 answer
-
answered 2022-05-04 12:45
Eugene Astafiev
I suppose the difference is in the authentication method.
To configure your device or application, connect directly to Microsoft 365 or Office 365 using the
SMTP AUTH
client submission endpointsmtp.office365.com
. See Enable or disable authenticated client SMTP submission (SMTP AUTH) in Exchange Online for more information.
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
Fluent Validation with conditions in asp.net core
I am working in asp. net core 6.0 web API project (clean architecture (CQRS)).
I am using fluent validation for validate command and queries.
public class CreateSiteDestinationSectionsCommand : IRequest<x> { public int DestinationSectionId { get; set; } public int DestinationSectionTitleId { get; set; } public int SiteCodeId { get; set; } public string Description { get; set; } public List<DestinationImageDto> Images { get; set; } public List<string> Links { get; set; } }
This is i did inside CreateSiteDestinationSectionsCommandHandler.
var DestinationSectionTitleId = request.DestinationSectionTitleId; if (DestinationSectionTitleId != 10) { if (DestinationSectionTitleId == 1 || DestinationSectionTitleId == 2 || DestinationSectionTitleId == 5 || DestinationSectionTitleId == 7 || DestinationSectionTitleId == 8 || DestinationSectionTitleId == 9 || DestinationSectionTitleId == 11) { var sectionimageCount = request.Images.Count; if (sectionimageCount != 1) { throw new ApiValidationException("Section has not more than one image"); } else (DestinationSectionTitleId == 10 && request.Images != null) { var sectionimageCount = request.Images.Count; if (sectionimageCount != 0) { throw new ApiValidationException("Section doesnot have any image"); } } } }
But instead of handling validation inside commandHandler, I have to handle validation in CreateSiteDestinationSectionsCommandValidator.
I tried this,
RuleFor(x => x.Images) .Must(x => x != null) .When(x => x.DestinationSectionId != 10) .WithMessage("Site Section image required"); RuleFor(x => x.DestinationSectionId).NotEmpty(); RuleFor(x => x.Images) .Must(x => x.Count != 1) .When(x => x.DestinationSectionId == 1 && x.DestinationSectionId == 1 && x.DestinationSectionId == 2 && x.DestinationSectionId == 5 && x.DestinationSectionId == 7 && x.DestinationSectionId == 8 && x.DestinationSectionId == 9 && x.DestinationSectionId == 11 ) .WithMessage("Site Section has not more than one image"); }
When I check throug postman request, Even I send with DestinationSectionId = 10 (and not sending any images), I got validation error as
"errors": { "Images": [ "Site Section image required" ] }
And Even I send more than 1 images for DestinationSectionId = 1, I did not get validation error. BUT I shoud get validation error as
Site Section has not more than one image
Why this validations not work correctly? What I missed?
-
Using RestSharp to request a file fails with memory issue
I have to API's talking to each other on Kubernetes. The first API asks the second API for a small file using RestSharp (in ASP.NET). The file is 8Kb so basically not large at all.
Yet i get the following message on the API that wants to receive the file:
Exception of type 'System.OutOfMemoryException' was thrown. at RestSharp.RestClient.ThrowIfError(RestResponse response) at RestSharp.RestClientExtensions.GetAsync(RestClient client, RestRequest request, CancellationToken cancellationToken) at Aftermarket.Server.AdministrationService.Server.Services.Services.RunSessionService.DownloadRunSession(String foldername) in /src/Aftermarket.Server.DbApi/Server/Services/Services/RunSessionService.cs:line 59
The code U use to call the other API and ask for the file looks as follows:
public async Task<byte[]> DownloadRunSession(string foldername) { try { var request = new RestRequest($"{config["WebApiServer:WebApiServerUrl"]}/blob/{foldername}"); var response = await client.GetAsync(request); if (!response.IsSuccessful) { Console.WriteLine("File download failed"); Console.WriteLine(response.StatusCode); return null; } return response.RawBytes; }catch(Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); return null; } }
The API that responds by sending the file has the following controller method:
public IActionResult GetBlob([FromQuery] string folderName, [FromServices] GetBlobsService _getBlobsService) { _logger.Info(folderName); Guid guid = Guid.NewGuid(); if (_env.EnvironmentName == "dev" || _env.EnvironmentName == "prod") { byte[] blob = _getBlobsService.GetBlob(folderName, guid, _logger); if (blob == null) return this.NotFound(); else { return File(blob, "application/force-download", guid + ".zip"); } } else { return Content("This function is only available in Dev/Uat Environment"); } }
Any one have any idea how a 8Kb file is causing this issue?
-
How is Windows Authentication Wired Up?
I'm in the process of creating an ASPNET Core 6 MVC app in VS 2022 which will eventually be deployed in a Docker container. Windows Authentication will be used as it's an internal app. When creating this project from scratch with File -> New Project -> ASP.NET Core 6 Web App (Model-View-Controller) and with Windows Authentication enabled, everything works as expected.
This is where it gets weird. Since this will be a Docker container on Linux, I commented out the IIS settings in launchSettings.json.
{ //"iisSettings": { // "windowsAuthentication": true, // "anonymousAuthentication": false, // "iisExpress": { // "applicationUrl": "http://localhost:60583", // "sslPort": 44391 // } //}, "profiles": { "ASPNETCORE6": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, "applicationUrl": "https://localhost:7276;http://localhost:5276", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
To recreate this issue, comment out the following from the generated Program.cs file:
//using Microsoft.AspNetCore.Authentication.Negotiate; //builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) // .AddNegotiate(); //builder.Services.AddAuthorization(options => //{ // options.FallbackPolicy = options.DefaultPolicy; //}); //app.UseAuthentication(); //app.UseAuthorization();
Now, when I run a debugging session using IIS Express, the browser windows renders with my correct domain name being displayed. How is this even possible? Is something being cached? Also, the browser is going to http://localhost:44391/ when debugging with IIS Express even though this is commented out in launchSettings.json.
Note: Windows authentication is not working when I debug with Kestrel, which is what I would expect.
-
how can anyone send email to me on my website in js
I am creating a project as I have created a contact page. I want any user to send me a email by putting his email and message in input box of contact page. I have also tried smtpjs but with that I can send the email from my side and registered email on smtpjs but unknown user who put his email without putting his password can't send email to me
for eg-
my email - myemail@gmail.com
my password - mypassword
unknown user email - unknown@gmail.com
how can unknown user send me email by putting only his email on my website contact page
any js library and js code can use for this problem please tell me
-
Please help to find email out of this cipher
Please help me to extract the email from this cipher, i am not been able to identify what type of hash or cipher is this.email is encoded in this hash please help me find the email.
1AAXs0RyFR3OM9nZA3XVkD07AVOZmYUMsRvyeq2BoY42sNbkSUySHCdFdwwQx6LWghNDqiPyBzNE7KDXkerX4vt0klZ2
-
SMTP client send QUIT command before waitting for OKAY from server
There's a smtp issue here and it's weired. Our business partner failed to send email to us lately. After checking, we found our partner's smtp server sent QUIT command immediately after email content, before waiting for 250 OKAY from us. It causes the connection shutdown and our smtp server thinks the transaction is incomplete and drops the email.
It looks like against the RFC standard of SMTP protocol. Who has experienced this before? Thanks in advance!
- Outlook VSTO - Get all items in a group calendar
-
How to set outlook addins pinned right away?
I set the SupportsPinning to true for outlook addins by modifying the manifest file as shown below. This allows the pin icon available. By default, the Pin is not selected. So is there a way to have the addins PINNED right away?
<!-- Task pane button --> <Control xsi:type="Button" id="msgReadOpenPaneButton"> ...... <Action xsi:type="ShowTaskpane"> <SourceLocation resid="readTaskPaneUrl" /> <SupportsPinning>true</SupportsPinning> </Action> </Control>
-
Send SVG image content to email as HTML using boto3
I want to send SVG content (without saved file) as HTML to Outlook email address. This SVG content works fine in browser showing a circle image, however sending it via boto3.client to Outlook email results in empty mail. Why? Any suggestions appreciated.
import io import json import boto3 from botocore.exceptions import ClientError SENDER = "Name1 LastName1 <Name1.LastName1@mail.com>" RECIPIENT = "Name2 LastName2 <Name2.LastName2@mail.com>" AWS_REGION = "us-east-1" SUBJECT = "something" svg = """ <svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg> """ BODY_HTML = f"""<html> <body> {svg} </body> </html> """ CHARSET = "UTF-8" client = boto3.client('ses',region_name=AWS_REGION) try: response = client.send_email( Destination={ 'ToAddresses': [ RECIPIENT ], }, Message={ 'Body': { 'Html': { 'Charset': CHARSET, 'Data': BODY_HTML } }, 'Subject': { 'Charset': CHARSET, 'Data': SUBJECT }, }, Source=SENDER ) except ClientError as e: print(e.response['Error']['Message']) else: print("Email sent! Message ID:"), print(response['MessageId'])
-
System.ObjectDisposedException' getting exception while creating multiple eml file at a time
string strMessage = String.Empty; while (true) { try { strMessage = Read(); } catch (Exception e) { //a socket error has occured Log.Error(e, e.Message); break; }
if (strMessage.Length > 0) { if (strMessage.StartsWith("QUIT")) { _client.Close(); break;//exit while } //message has successfully been received if (strMessage.StartsWith("EHLO")) { Write("250 OK"); } if (strMessage.StartsWith("RCPT TO")) { Write("250 OK"); } if (strMessage.StartsWith("MAIL FROM")) { Write("250 OK"); } else { _client.Close(); break;//exit while }
I am trying to call multiple request at a time and create multiple eml file at a time but I am getting System.ObjectDisposedException' . this is my Read() method
private String Read() {
byte[] messageBytes = new byte[8192]; int bytesRead = 0; NetworkStream clientStream = _client.GetStream(); ASCIIEncoding encoder = new ASCIIEncoding(); bytesRead = clientStream.Read(messageBytes, 0, 8192); string strMessage = encoder.GetString(messageBytes, 0, bytesRead); return strMessage; }
-
How do I call a method to automatically send an email in the controller?
I need to be able to send automatic emails to any users who have registered new accounts, changed passwords, and/or created new orders.
I've been given the SendEmail file, which belongs in the "Utilities" folder in my solution.
using System; using System.Net.Mail; using System.Net; namespace SendEmail { public static class EmailMessaging { public static void SendEmail(String toEmailAddress, String emailSubject, String emailBody) { //Create a variable for YOUR TEAM'S Email address //This is the address that will be SENDING the emails (the FROM address) String strFromEmailAddress = "email@gmail.com"; //This is the password for YOUR TEAM'S "fake" Gmail account String strPassword = "Password"; //This is the name of the business from which you are sending //TODO: Change this to the name of the company you are creating the website for String strCompanyName = "Team Final Project"; //Create an email client to send the emails //port 587 is required to work, do not change it var client = new SmtpClient("smtp.gmail.com", 587) { UseDefaultCredentials = false, //This is the SENDING email address and password //This will be your team's email address and password Credentials = new NetworkCredential(strFromEmailAddress, strPassword), EnableSsl = true }; //Add anything that you need to the body of the message //emailBody is passed into the method as a parameter // /n is a new line – this will add some white space after the main body of the message //TODO: Change or remove the disclaimer below String finalMessage = emailBody + "\n\n Thank you, come back again soon!"; //Create an email address object for the sender address MailAddress senderEmail = new MailAddress(strFromEmailAddress, strCompanyName); //Create a new mail message MailMessage mm = new MailMessage(); //Set the subject line of the message (including your team number) mm.Subject = "Team ## - " + "Thank you!"; //Set the sender address mm.Sender = senderEmail; //Set the from address mm.From = senderEmail; //Add the recipient (passed in as a parameter) to the list of people receiving the email mm.To.Add(new MailAddress(toEmailAddress)); //Add the message (passed) mm.Body = finalMessage; //send the message! client.Send(mm); } } }
My problem is that neither I nor my team members know how to implement call this from the controller in a way that will be sent automatically and with the user's email and name. We imagine they will be in the Account and Orders controllers. The accounts controller has the register and change password methods, which work, and the orders controller has the complete order method.
Also, we are not using a confirmation view, it has to be an automatic email.
We need some direction in figuring out where exactly we need to call the method from and how.
The most helpful thing I've found on the internet today is this block of code for a test message that is not intended to be sending automatic emails.
public static void CreateTestMessage(string server) { MailAddress from = new MailAddress("sender@gmail.com", "Team Project"); MailAddress to = new MailAddress("reciever@gmail.com", "Customer"); MailMessage message = new MailMessage(from, to); message.Subject = "Password Changed"; message.Body = @"This is a confirmation email that your password has been changed."; SmtpClient client = new SmtpClient(server); client.Credentials = CredentialCache.DefaultNetworkCredentials; try { client.Send(message); } catch (Exception ex) { Console.WriteLine("Exception caught in CreateBccTestMessage(): {0}", ex.ToString()); } }
Everything is being coded on MS VS