how python smtplib work without specifying port? - smtp

I am using smtplib to send email to people in my company from a company mail server. The code here works fine. I just wonder how it works without a need to provide the port in smtplib.SMTP(). Additionally, I can define any sender address within a company domain and I am curious how it works like this. I'd appreciate if someone explains this to me or share a link so I learn about this.
def send_email(subject, sender, receiver):
msg = MIMEMultipart("alternative")
msg['Subject'] = subject
msg['From'] = sender
if type(receiver) is list:
msg['To'] = ", ".join(receiver)
else:
msg['To'] = receiver
# html message here
content = MIMEText(html, "html")
msg.attach(content)
content = MIMEText(html, "html")
with smtplib.SMTP('mailserver.companydomain.com') as smtp:
smtp.sendmail(sender, receiver,msg.as_string())

Related

OperationalError (1366, "Incorrect string value: '\\xE2\\x80\\x8ESen...') MySQL Django

I develop django website on cpanel with MySQL database. I have a function that pull feeds from this website https://travelcommunication.net/feed/ and create an object from that (web scraping using beautifulsoup4).
But when I try to grab the content section, the error appears. But that only happens with certain items, not all.
I try on my local (with sqlite database) and all working fine. I have also tried on heroku (with PostgreSQL database) and all working fine.
Here is my code:
#views.py
def pull_feeds(request, pk):
if request.user.is_superuser:
source = Autoblogging.objects.get(pk=pk)
url = requests.get(source.url)
soup = BeautifulSoup(url.content, "html.parser")
length = source.items
items = soup.find_all('item')[:length]
contents = soup.find_all('content:encoded')[:length]
for i in range(length-1, -1, -1):
content = contents[i].text
title = items[i].title.text
body = content[content.find('<p>'):] #the problem is here .. when i comment this, everything works fine
category = Category.objects.get(pk=source.category.id)
if not Post.objects.filter(title=title).exists():
post = Post(title=title,
body=body, #the problem is here .. when i comment this, everything works fine
category=category)
link = content[content.find('src=')+5:content.find('alt')-2]
img_data = requests.get(link).content
with open('temp_image.jpg', 'wb') as handler:
handler.write(img_data)
with open('temp_image.jpg', 'rb') as handler:
file_name = link.split("/")[-1]
post.cover.save(file_name, files.File(handler))
os.remove("temp_image.jpg")
return redirect("news:autoblogging")
else:
return HttpResponse("Sorry you are not allowed to access this page")
Does anyone know how to fix this error? Thanks.

cant send message with facebook graph api

in my django project
i have this function:
def mesaj_yolla():
fbid="my_facebook_id"
post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<my_access_token>'
response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":"hello"}})
status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg)
print(status)
it returns: <Response [400]>
what is wrong with these codes? i just want to send a message to user.
According to the API documentation, you should use recipients.id instead of recipients.user_id:
def mesaj_yolla():
fbid="my_facebook_id"
post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<my_access_token>'
response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text":"hello"}})
status = requests.post(post_message_url, headers={"Content-Type": "application/json"},data=response_msg)
print(status)
That explains the HTTP 400 code (Bad request).

How get the current user's own email address or check entered, using Exchange Web Services (EWS)?

I have to work with external Exchange server. How can I get the own email address or check address entered by the user (that he introduced exactly own address), using EWS?
Email address is not the same as username.
The best solution at this moment.
You can use ConvertId with a generic address and Exchange will then return the PrimarySMTP for that mailbox eg.
Folder Inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
AlternateId aiAlternateid = new AlternateId(IdFormat.EwsId, Inbox.Id.UniqueId, "mailbox#domain.com");
AlternateIdBase aiResponse = service.ConvertId(aiAlternateid, IdFormat.EwsId);
Console.WriteLine(((AlternateId)aiResponse).Mailbox);
You might have some luck with the method ResolveName. Using this method you can search the Global Address List for the user. And by using a simple if else to see if any results were returned. This method does resolve ambiguous names so be sure to check the result carefully
Example:
NameResolutionCollection coll = service.ResolveName("Johnson", folders, ResolveNameSearchLocation.DirectoryOnly, false);
foreach (NameResolution nameRes in coll)
{
Console.WriteLine("Contact name: " + nameRes.Mailbox.Name);
Console.WriteLine("Contact e-mail address: " + nameRes.Mailbox.Address);
Console.WriteLine("Mailbox type: " + nameRes.Mailbox.MailboxType);
}
If you want to read more about it: https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.exchangeservice.resolvename(v=exchg.80).aspx
Based on iCode4U's Answer, if your service uses default credentials (from the logged user), then this might get what you need:
String address = service.ResolveName(Environment.UserName)(0).Mailbox.Address;
EDIT: If one can't trust the uniqueness of the results brought by the query above, then it is better to use something like this (this would work in my organization, where usernames are also email identifiers, but each one must tweak it to fit his own scenario):
string address = Service.ResolveName(Environment.UserName).Select(
a => a.Mailbox.Address).FirstOrDefault(
b => b.StartsWith(Environment.UserName + "#",
StringComparison.InvariantCultureIgnoreCase));
We use this function loaded in the user PowerShell profile.
Function CurrentUserPrimarySmtpAddress()
{
<#
.SYSNOPSIS
Attempt to retrieve the current user's primary SMTP address.
.DESCRIPTION
Attempt to retrieve the current user's primary SMTP address.
.NOTES
Author: David Barrett
Date Created: 08NOV2016
.LINK
https://gallery.technet.microsoft.com/office/PowerShellEWS-Update-items-48c3dcfc
.EXAMPLE
$PrimarySmtpAddress = CurrentUserPrimarySmtpAddress
#>
$searcher = [adsisearcher]"(samaccountname=$env:USERNAME)"
$result = $searcher.FindOne()
if ($result -ne $null)
{
return $result.Properties["mail"]
}
return $null
}

Adding http headers to sunspot rails request

We are using sunspot-rails to connect to websolr. I am trying to find out a way to add http headers to the outgoing request. The samples are present only for rsolr but not for sunspot-rails.(https://github.com/onemorecloud/websolr-demo-advanced-auth).
The purpose is to use the headers for authentication.Is there a way to add/modify http headers from sunspot-rails for both indexing and querying calls?
I think I found the answer to this:
https://groups.google.com/forum/#!searchin/ruby-sunspot/authentication/ruby-sunspot/-FtTQdg4czs/mvOuB7g8yCgJ
The example quoted by outoftime in this would be the solution to retrieve the http object.
class SolrConnectionFactoryWithTimeout
def initialize(timeout = 60)
#timeout = timeout
end
def connect(opts = {})
client = RSolr.connect(opts)
solr_connection = client.connection
http = solr_connection.connection
http.read_timeout = #timeout
client
end
end
Sunspot::Session.connection_class =
SolrConnectionFactoryWithTimeout.new(timeout.to_f)
Then use in combination with
http://ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Setting+Headers
req = Net::HTTP::Get.new(uri)
req['If-Modified-Since'] = file.mtime.rfc2822

Accessing a request's body using classic ASP?

How do I access what has been posted by a client to my classic ASP server?
I know that there is the Request.Forms variable, but the client's request was not made using a Form.
The client request's body is just a string made using a standard POST statement.
Thanks
You need to read request bytes if content type of request sent by client is not form data. In this case, request is not a form-data that is accessible through name-value pairs so you cannot use Request.Form collection. I suggest investigate the BinaryRead method.
Reading posted data and convert into string :
If Request.TotalBytes > 0 Then
Dim lngBytesCount
lngBytesCount = Request.TotalBytes
Response.Write BytesToStr(Request.BinaryRead(lngBytesCount))
End If
Function BytesToStr(bytes)
Dim Stream
Set Stream = Server.CreateObject("Adodb.Stream")
Stream.Type = 1 'adTypeBinary
Stream.Open
Stream.Write bytes
Stream.Position = 0
Stream.Type = 2 'adTypeText
Stream.Charset = "iso-8859-1"
BytesToStr = Stream.ReadText
Stream.Close
Set Stream = Nothing
End Function
Hope it helps.
Update #1:
With using JScript
if(Request.TotalBytes > 0){
var lngBytesCount = Request.TotalBytes
Response.Write(BytesToStr(Request.BinaryRead(lngBytesCount)))
}
function BytesToStr(bytes){
var stream = Server.CreateObject("Adodb.Stream")
stream.type = 1
stream.open
stream.write(bytes)
stream.position = 0
stream.type = 2
stream.charset = "iso-8859-1"
var sOut = stream.readtext()
stream.close
return sOut
}
To get the JSON string value just use CStr(Request.Form)
Works a treat.
In Classic ASP, Request.Form is the collection used for any data sent via POST.
For the sake of completeness, I'll add that Request.QueryString is the collection used for any data sent via GET/the Query String.
I would guess based on the above that even though the client is not a web browser, the Request.Form collection should be populated.
note: all of this is assuming the data being sent is textual in nature, and that there are no binary uploads (e.g. pictures or files) being sent. Update your question body if this is an incorrect assumption.
To test, write out the raw form data and see what you have - something along the lines of:
Response.Write(Request.Form)
Which with a regular web page will output something like
field=value&field2=value2
If you get something along those lines, you could then use that as a reference for a proper index.
If you do not get something like that, update your question with what you tried and what you got.