I try to use the sample in the robotframework-imaplibrary:
Open Mailbox host=imap.domain.com user=${mail} password=${PW}
${LATEST} = Wait For Email sender=${sender} timeout=300
${parts} = Walk Multipart Email ${LATEST}
:FOR ${i} IN RANGE ${parts}
\\ Walk Multipart Email ${LATEST}
\\ ${content-type} = Get Multipart Content Type
\\ Continue For Loop If '${content-type}' != 'text/html'
\\ ${payload} = Get Multipart Payload decode=True
\\ Should Contain ${payload} your email
\\ ${HTML} = Open Link From Email ${LATEST}
\\ Should Contain ${HTML} Your email
Close Mailbox
I get the error for the 3rd line ( ${parts} = Walk Multipart Email ${LATEST} ) after the test run:
TypeError: initial_value must be str or None, not bytes
Does anyone know a working example of an email checking?
Related
When forwarding an email through AWS SES using boto3, I am failing either to keep the attachment, or sending the email altogether if the 'From' header contains a special character.
I have tried this using SES resource's two functions, send_email and send_raw_email.
I can send emails just fine with the send_email function, except I could not find a way to keep any attachments.
I can send emails with attachments that have regular 'From' headers with send_raw_email, but if there is a special character in the 'From' header, I receive the below error:
When From is encoded with UTF-8:
An error occurred (InvalidParameterValue) when calling the SendRawEmail operation: Missing final '#domain'"
When From is encoded with ascii:
An error occurred (InvalidParameterValue) when calling the SendRawEmail operation: Local address contains control or whitespace
I have read through many SO posts, where examples with attachments always use the send_raw_email function. This makes sense to me as the send_email function only accepts a Body field from what I can tell, whereas send_raw_email accepts the email object in byte form. However, they seem to ignore the possibility of special characters in the 'From' header, or I am doing something wrong.
How can I avoid the above errors and preferably retain the original From header while also retaining any attachments?
Below is some simplified code that I use:
s3 = boto3.client("s3")
data = s3.get_object(Bucket=EMAIL_BUCKET, Key=f"{INCM_PREFIX_RAW}/{message_id}")
contents = data["Body"].read()
message = email.message_from_string(contents.decode("utf-8"))
characters = {"Ğ": "G", "Ü": "U", "Ş": "S", "İ": "I", "Ö": "O", "Ç": "C",
"ğ": "g", "ü": "u", "ş": "s", "ı": "i", "ö": "o", "ç": "c", '"': "", " ": ""}
for character in characters: message_from = message_from.replace(character, characters[character])
if "<" in message_from:
sender = message_from.split("<")[0]
if "#" in sender: sender = "<example#example.com>"
else: sender = sender + "<example#example.com>"
else: sender = "<example#example.com>"
message["From"] = sender
ses_client = boto3.client("ses")
response = ses_client.send_raw_email(
Destinations=[destination],
RawMessage={"Data": message.as_bytes()}
)
Here is the alternative approach of how I use the send_email function:
response = ses_client.send_email(
Source=message["From"], Destination={"ToAddresses": [destination]},
Message={"Subject": {"Data": message["Subject"]},
"Body": {"Html": {"Data": message_html, "Charset": "utf-8"}}},
ReplyToAddresses=[message_from], ReturnPath=message["From"]
)
Notes: I am using From as an address from my own domain, preceded by the original senders name, such as '"John Doe" <my#domain.com>'
I have a flask application, where I want to send an email, along with some data fetched from a form. Everything works fine, but the issue is, that when the email is received the HTML code is not rendered it is only displayed the raw code. Here is what I have done so far
if google_response['success']: #this line is used for a ReCaptcha response
msg = Message('Thank you for contacting me', sender='(my email address is put here as a string)', recipients=[request.form['email']])
name = request.form['name']
msg.body = render_template('email.html', name=name)
mail.send(msg)
return render_template('index.html')
else:
return render_template('index.html')
What, am I doing wrong?
I am assuming this has to do with how you are creating your email. You should be using a Multipart Email to do so. My guess would be that you're using using your HTML as the text for the email and not actually attaching it to the email.
Since you haven't provided us with any of that code, I'll give you an example of how to generate an email that includes HTML formatting.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
to_address = ''
from_address = ''
msg = MIMEMultipart('alternative')
msg['Subject'] = ''
msg['From'] = from_address
msg['To'] = to_address
text = ''
html = 'your HTML code goes here'
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('', '')
mail.sendmail(to_address, from_address, msg.as_string())
mail.quit()
I need to send an email from an MS Access database with an attachment (not an Access object, but a separate file), but not tied to any one email software (Groupwise, Outlook, etc). I have found code to send an email with an attachment using Groupwise and Outlook, and there is the generic DoCmd.SendObject which only appears to support attaching Access objects. Is there a way to send an email from Access with an attachment, regardless of the email client configured on the user's PC?
Rationale: There's complications with software rollout here. The machine I work on has Access 2013 and Outlook 2013 installed. The users of the database are running Access 2010, but when I compile the database into a .accde in 2013, it does not work on 2010. The only way I can get it to work is to compile it on a much older PC also running Access 2010. However, this old PC does not have Outlook and IT won't/can't install Outlook on it. This means I can't compile the database using the Outlook library, as there is no Outlook library on the machine.
Here is code I use to send e-mails using Gmail:
Public Function SendEmailViaGmail(SendTo As String, Optional Subject As String = "", Optional TextBody As String = "", Optional ReplyTo As String = "", Optional AttachedFiles As Variant = "") As String
On Error GoTo send_emailErr
Dim ErrNum As Long
Dim ErrDes As String
SendEmailViaGmail = ""
ErrNum = 0
Set cdomsg = CreateObject("CDO.message")
With cdomsg.Configuration.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'NTLM method
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 587
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = sendusername '
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = sendpassword
.Update
End With
' build email parts
With cdomsg
.To = SendTo
.FROM = sendusername
.Subject = Subject
.TextBody = TextBody & vbCrLf & vbCrLf & vbCrLf & "--" & vbCrLf & "Sent using Marlan Data-Systems"
If IsArray(AttachedFiles) Then
For Each AttachedFile In AttachedFiles
If Len(AttachedFile) > 3 Then .AddAttachment AttachedFile
Next
Else
If Len(AttachedFiles) > 3 Then .AddAttachment AttachedFiles
End If
.send
End With
SendEmailViaGmail = "Done!"
send_emailExit:
Set cdomsg = Nothing
Exit Function
send_emailErr:
ErrNum = Err.Number
ErrDes = Err.Description
Select Case Err.Number
Case -2147220977 'Likely cause, Incorrectly Formatted Email Address, server rejected the Email Format
SendEmailViaGmail = "Please Format the Email Address Correctly."
Case -2147220980 'Likely cause, No Recipient Provided (No Email Address)
SendEmailViaGmail = "Please Provide an Email Address"
Case -2147220960 'Likely cause, SendUsing Configuration Error
SendEmailViaGmail = "SendUsing Configuration Error"
Case -2147220973 'Likely cause, No Internet Connection
SendEmailViaGmail = "Please Check Internet Connection"
Case -2147220975 'Likely cause, Incorrect Password
SendEmailViaGmail = "Please Check Password"
Case Else 'Report Other Errors
SendEmailViaGmail = ""
End Select
SendEmailViaGmail = SendEmailViaGmail & " Error number: " & Err.Number & " Description: " & Err.Description
'If ErrNum = -2147220975 Then
' cdomsg.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 465
' Resume
'End If
Resume send_emailExit
End Function
AttachedFiles is a String, or an Array of Strings, representing full paths to file or files that are to be attached to the email.
CDO.message is a Microsoft windows object.
You can replace value of smtpserver to some other mailing service. If you do so, please be sure to modify other parameters as well.
Code is based on code I found on the web.
I'm writing a script to send an email to more than one email account, but not able, yet.
It works as it is below, but if I set receivers='xxx#xxx.com','yyy#yyy.com' it won't work, it throws an error:
AttributeError: 'tuple' object has no attribute 'encode'.
How can I set receivers=?
def send_email (out_file):
sender = 'xxx#xxx.com'
receivers = 'xxx#xxx.com'
email_pass = 'aaaa'
filematch=re.findall('NE.*\.txt',out_file.name)
subject = ("NEXXXX_price_update")
message = ("The following file was forwarded to your ftp account %s " %filematch)
msg = 'Subject: %s\n%s' %(subject, message)
try:
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com',0)
smtpObj.login(receivers, email_pass)
smtpObj.sendmail(sender, receivers, msg)
print ("Successfully sent email")
except SMTPException:
print ("email NOT successful")
print(SMTPException.__cause__)
smtpObj.quit()
You assign wrongly
receivers='xxx#xxx.com','yyy#yyy.com'
You suppose to assign as a tuple or list, not sure 100% which.
Give a try:
receivers=('xxx#xxx.com','yyy#yyy.com')
or
receivers=['xxx#xxx.com','yyy#yyy.com']
def email_for_task_release_data(server,from,recipients,subject,body)
puts "Sending Email"
mailer = ModokMailer.new(from)
recipients.each do |to|
mailer.add_recipients(to)
end
mailer.add_subject(subject)
mailer.add_body(body)
mailer.send(server)
end
results_acunote_1.each do |row|
body += "#{row['rel_type']}\t\t#{row['us']}\t#{row['uk']}\t#{row['jv']}\t#{row['ca']}\t #{row['au']}\t\t #{row['total']}\n"
Email output vs output displayed on terminal using puts1