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']
Related
I am trying to send a mail through an AWS Glue job. The mail will have multiple number of attachments that it gets from the s3 bucket. According to the logs, it is running until server.login(). It is failing in the server.sendmail() function.
Following is the code -
def sendEmail(TO, SUBJECT, BODY_HTML):
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = ','.join(RECIPIENT + TO)
part1 = MIMEText(BODY_HTML, 'html')
msg.attach(part1)
s3 = boto3.resource('s3')
bucket = s3.Bucket('sample-bucket')
for obj in bucket.objects.filter(Delimiter='/', Prefix='sample-folder/'):
filename = ((obj.key).split("/")[1])
s3_object = s3_obj.s3_get_object(sample-bucket, 'sample-folder/'+ filename)
body = s3_object['Body'].read()
part = MIMEApplication(body, filename)
part.add_header("Content-Disposition", 'attachment', filename=filename)
msg.attach(part)
try:
server = smtplib.SMTP(HOST, PORT)
server.ehlo()
server.starttls()
server.ehlo()
server.login(USERNAME_SMTP, PASSWORD_SMTP)
server.sendmail(SENDER, RECIPIENT, msg.as_string()) ***--Error***
server.close()
print (msg)
print ("Email sent")
I am getting the following error -
Error: (554, b'Transaction failed: Expected '=', got "null"')
What is the issue?
I got the answer. The problem was with the way files were read from s3. The output of the first iteration was -
sample-bucket/sample-folder/
So, it was taking a null object and failing. So, I just skipped the first object in the iteration and carried out the whole thing. It worked.
Please find the final code below -
def sendEmail(TO, SUBJECT, BODY_HTML):
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = ','.join(RECIPIENT + TO)
part1 = MIMEText(BODY_HTML, 'html')
msg.attach(part1)
s3 = boto3.resource('s3')
bucket = s3.Bucket('sample-bucket')
**it = iter(bucket.objects.filter(Delimiter='/', Prefix='sample-folder/'))
next(it, None)
for obj in it:**
filename = ((obj.key).split("/")[1])
s3_object = s3_obj.s3_get_object(sample-bucket, 'sample-folder/'+ filename)
body = s3_object['Body'].read()
part = MIMEApplication(body, filename)
part.add_header("Content-Disposition", 'attachment', filename=filename)
msg.attach(part)
try:
server = smtplib.SMTP(HOST, PORT)
server.ehlo()
server.starttls()
server.ehlo()
server.login(USERNAME_SMTP, PASSWORD_SMTP)
server.sendmail(SENDER, RECIPIENT, msg.as_string())
server.close()
print (msg)
print ("Email sent")
Below is my VBScript code to send an email with a file attached. The file is present at a location which I need to grab when sending the email.
Set objMessage = CreateObject("CDO.Message")
Set args = WScript.Arguments
Set arg1 = args.Item(0)
objMessage.Subject = "Sample subject"
objMessage.From = "test#gmail.com"
objMessage.To = "test2#gmail.com"
objMessage.TextBody = "Please see the error logs attached with this email"
objMessage.AddAttachment ""&arg1&""
'==This section provides the configuration information for the remote SMTP server.
'==Normally you will only change the server name or IP.
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "hostname"
'Server port (typically 25)
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update
'==End remote SMTP server configuration section==
objMessage.Send
To run this script through command line I use:
>cscript sendemail.vbs D:\users\me\Desktop\readme.txt
When I run this I get an error saying:
D:\Users\me\Desktop\sendemail.vbs(3, 1) Microsoft VBScript runtime error: Object required: '[string: "D:\Users\me\Desk"]'
Any suggestions what could be wrong with this?
The error message actually says it all. While the Arguments collection is an object, its first element is not. It's a string, which in VBScript is a primitive data type. The Set keyword is exclusively for assigning objects to variables. Primitive data types are assigned by just using the assignment operator.
Change this:
Set arg1 = args.Item(0)
into this:
arg1 = args.Item(0)
and the error will disappear.
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 tried to use example (with my login and pass) from http://dlang.org/phobos/std_net_curl.html#.SMTP
But every time I am getting error: std.net.curl.CurlException#std\net\curl.d(3691): Failed sending data to the peer on handle 7F6D08.
What's wrong? I tried to specify port (465) but it's not helped.
import std.net.curl;
// Send an email with SMTPS
auto smtp = SMTP("smtps://smtp.gmail.com");
smtp.setAuthentication("from.addr#gmail.com", "password");
smtp.mailTo = ["<to.addr#gmail.com>"];
smtp.mailFrom = "<from.addr#gmail.com>";
smtp.message = "Example Message";
smtp.perform();
When sending an email from C# with body being large is resulting in failure in sending email
Mailbox unavailable.
The email is working fine with a smaller body. I am using html body to true property..
Thanks,
Zafar
Code:
using (MailMessage _mailMsg = new MailMessage())
{
_mailMsg.From = new MailAddress(ConfigurationManager.AppSettings["mailFrom"].ToString());
_mailMsg.Body = mail.Body;
_mailMsg.Subject = mail.Subject;
_mailMsg.IsBodyHtml = true;
foreach (string strEmailIds in mailTo)
{
if (strEmailIds != null && strEmailIds != string.Empty && strEmailIds != "")
{
if (!_mailMsg.To.Contains(new MailAddress(strEmailIds)))
_mailMsg.To.Add(new MailAddress(strEmailIds));
}
}
//_mailMsg.CC.Add(ConfigurationManager.AppSettings["mailCC"].ToString());
using (SmtpClient _client = new SmtpClient(ConfigurationManager.AppSettings["Host"].ToString()))
{
if (_mailMsg.To.Count > 0)
{
_client.Send(_mailMsg);
}
else
{
_mailMsg.Subject = "No emails associated with the portfolio: " + account + " Original Email:" + mail.Subject;
_mailMsg.To.Add(new MailAddress(ConfigurationManager.AppSettings["mailSuppotTeam"].ToString()));
_client.Send(_mailMsg);
}
Oke, on thing it could be is that the mail server rejects big messages. Let exclude that one... I assume you have a local smtp mail server installed (check for telnet 127.0.0.1 25 that should give a sort of reply) configure the mail server [ConfigurationManager.AppSettings["Host"]] for 127.0.0.1, can you send big mails now?
If ConfigurationManager.AppSettings["Host"] is already the local SMTP server then:
a) stop that smtp service (Simple Mail Transfer Protocol) for a moment (via the command services.msc)
b) send a small email
c) go to c:\inetpub\mailroot\pickup and edit the message via notepad so that it becomes a BIG email
d) start the smtp service again (services.msc)
The issue was with sending email to cross domain email id and was resulting in the Generic exception
"Mailbox unavailable." May be this is one of the reason behind the above exception.