Python问题,使用不同的模板发送批量电子邮件?

时间:2018-12-30 09:24:03

标签: python python-3.x email

我正在尝试使用Python自动执行我的冷电子邮件销售流程。我基本上想将大量信息放入Google表格中。 Google表格中的列值为 名称,电子邮件,公司,跟进,新闻项目。 根据以下值进行跟进(试图找出跟踪跟进#的方式):是,#1,#2,否

我能够从Google表格中读取数据,并且能够发送电子邮件。

这里是Google Sheet`。

这是我的代码:

import csv
import smtplib
import gspread
import pandas as pd
import pprint
from oauth2client.service_account import ServiceAccountCredentials
from emailsettings import USERNAME, PASSWORD
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)

sheets = client.open('Example').sheet1

sh = client.open_by_url('https://docs.google.com/spreadsheets/d/1RkzEkCJ4kEbdsW4-LqyO8bKTKBm9XlXrMp49UxIpotQ/edit#gid=0')
sheet = sh.get_worksheet(0)

data1 = sheet.get_all_values()

smtp = smtplib.SMTP('smtp.gmail.com',port=587,timeout=10)

smtp.starttls()
smtp.login(USERNAME,PASSWORD)

INITIAL_MESSAGE = """
Hi {},

I came across your name while looking for contacts at {}. Huge fan of your work. 

I'm a person and I'm the founder and COO of this company. This Company is a full-service internet marketing agency, specializing in social media advertising. We've worked with Fortune 500 Company and many others. 

I'm reaching out because we've helped several companies with increasing their ROI and wanted to see if you were open to discussing your digital goals for 2019. 

Would you be open to hop on a quick call? Here's my schedule for the week. 

Looking forward to hearing from you. 

Thanks, Name

PS: Congrats on the {}
"""

FOLLOW_UP = """
Hey {}, how's {}? Hope you're doing awesome. 

Reading more about your background, super impressed - by the way, congrats on {}. 

I briefed my team about doing social media ads for {} and they're super excited. 

Can you meet sometime this week? Otherwise, here's my schedule so pick a time that works well for you. 

Cheers, 
Name
"""


SECOND_FOLLOW_UP="""
Hey {}, 

Just wanted to see how things were going at {}. Just wanted to check if you were still interested in chatting sometime about working with Company. 

If you're interested, send me over a list of times so we can chat. 

Thanks, Name

PS: Congrats on {}

"""

smtp = smtplib.SMTP('smtp.gmail.com',port=587,timeout=10)

smtp.starttls()
smtp.login(USERNAME,PASSWORD)

iterdata = iter(data1)
next(iterdata)


for elem in data1:
    name, email, company, follow, news = elem

    if follow == 'No':
        subject = 'Hey {}, FOLLOW UP #1, {} and Company'.format(name, company, news)
        msg = FOLLOW_UP.format(name,company,company, news)



    elif follow =='1':
        subject = 'Hello, {}, FOLLOW UP #2'.format(company)
        msg = INITIAL_MESSAGE.format(name,company, news, company)


    elif follow =='2':
        subject = 'Hello again, {}, FOLLOW UP #3'.format(company)
        msg = SECOND_FOLLOW_UP.format(name,company, news)

    else:
        print('{}\n'.format(company))


    email_msg = 'Subject: {} \n\n {}'.format(subject, msg)    
    smtp.sendmail(from_addr=USERNAME ,to_addrs=email, msg=email_msg)

    print(email_msg)
smtp.quit()

它打印出“公司”,并给我这个错误:

NameError: name 'subject' is not defined

我的目标是在电子表格中填充有关电子邮件,个人,公司和新闻项目的信息。电子表格填满并运行脚本后,它将跟踪跟进的次数并根据多个可用模板生成电子邮件。

我听说通过创建类,方法和归因,这会更容易,但不确定如何做到这一点。

谢谢!

1 个答案:

答案 0 :(得分:0)

它抛出:

NameError: name 'subject' is not defined

因为这一行:

email_msg = 'Subject: {} \n\n {}'.format(subject, msg)    

请注意,您在"subject"范围内声明了一个名为if的变量,而不是在else范围内声明了该变量(该变量应包含要使用的“默认”值,不是吗?)

msg var也是如此,您以后使用以下格式:

email_msg = 'Subject: {} \n\n {}'.format(subject, msg)

执行以下操作:

...
else:
    subject = 'some default subject'
    msg = 'some default message'
    print('{}\n'.format(company))

[编辑]

或更妙的是,甚至在启动subject逻辑之前,用默认值声明msgif。匹配时,覆盖值。这样可以确保您使用已定义的var。

类似的东西:

for elem in data1:
    name, email, company, follow, news = elem

    subject = 'default subject' # ADD THIS LINE
    msg = 'default message' # ADD THIS LINE

    if follow == 'No':
        ...

[edit2] 要缩短您的代码(如您所述),请尝试重构为:

# mapping between 'follow' and (subject template and message template)
d = {'No': ('Hey {}, FOLLOW UP #1, {} and Company', FOLLOW_UP),
     '1': ('subject1', INITIAL_MESSAGE),
     '2': ('subject2', 'msg2'),
     }

for elem in data1:
    # elem should be namedTuple to hold all relevant data inside
    data = d.get(elem.follow, ('default subject', 'default message'))
    subject = data[0].format(**elem)
    msg = data[1].format(**elem)

    email_msg = 'Subject: {} \n\n {}'.format(subject, msg)
    smtp.sendmail(from_addr=USERNAME, to_addrs=elem.email, msg=email_msg)

    print(email_msg)