Exemple #1
0
def send_mail(path_image):

    user = yagmail.SMTP(user=usermail, \
                           password=passmail)
    user.send(to='*****@*****.**', \
         subject='Alerta Mascota en Sofá!', \
         contents= [yagmail.inline(path_image)])
def send_email():
    FROM = '*****@*****.**'
    TO = '*****@*****.**'
    subject = 'Inventory Report - GCP'
    #contents = '/tmp/inventory.txt'
    contents = [yagmail.inline('/tmp/inventory.txt')]
    yag = yagmail.SMTP(FROM, 'zmytgndtkxdukwwk')
    yag.send(TO, subject, contents)
Exemple #3
0
 def __emitirAlerta(self):
     try:
         deteccao_img = [yagmail.inline("./amostra.jpg")]
         yag = yagmail.SMTP(self.__email_remetente,
                            self.__senha_remetente)
         yag.send(self.__email_destinatario,
                  "WATCHER - Frontal ou corpo detectado", deteccao_img)
         os.remove("./amostra.jpg")
     except Exception as erro:
         Watcher.LOG(" Watcher.emitirAlerta ", erro)
def send_email(name, event, email, imgpath):
    # global PSLOGO, yag
    mailtext = 'Dear %s,\n\nThank you for participating in the event %s conducted during Phase Shift 2017 at BMSCE.\nPlease find your attached Participation e-Certificate. We look forward for your participation at Phase Shift 2018 as well!\n\nCheers!\nPhase Shift 2017 Team\n\n*** This is an automatically generated email, please do not reply to this message ***\nIn case of any discrepancy, please contact your Event Coordinator.\n\n' % (
        name, event)
    contents = [mailtext, inline(PSLOGO)]
    yag.send(email,
             'Phase Shift 2017 - %s Participation Certificate' % event,
             contents,
             attachments=imgpath)
    root.update()
Exemple #5
0
def sendmail():
    yag = yagmail.SMTP(user='******',
                       password='******',
                       host='smtp.qq.com')
    img_dir = 'C:/Users/吕发发/Pictures/1.png'
    contents = ['我就想给你发QQ邮箱', yagmail.inline(img_dir)]
    attachments = ['C:/Users/吕发发/Downloads/fushi.doc']
    persons = ['*****@*****.**']
    yag.send(to=persons,
             subject='测试自动发邮件',
             contents=contents,
             attachements=attachments)
Exemple #6
0
def main(run_id, sender_address, sender_password, receiver_address):
    yag = yagmail.SMTP(sender_address, sender_password)

    filename = "report_{}".format(run_id)
    jpg_filepath = os.path.join(report_dir, filename + ".jpg")

    subject = "Reports for {}".format(
        datetime.datetime.now().strftime("%Y-%m-%d"))

    yag.send(
        to=receiver_address,
        subject=subject,
        contents=yagmail.inline(jpg_filepath),
    )
Exemple #7
0
def create_emails():
    user_list, err = get_users()
    # record_confirmed = access.get_new_daily_record_confirmed('newConfirmed')
    # record_fatalities = access.get_new_daily_record_confirmed('newFatalities')
    top_5_most_confirmed_str, top_5_most_confirmed_df = access.get_top_n_countries(5, 'newConfirmed', None, 'most')
    top_5_most_fatalities_str, top_5_most_fatalities_df = access.get_top_n_countries(5, 'newFatalities', None, 'most')
    top_5_least_confirmed_str, top_5_least_confirmed_df = access.get_top_n_countries(5, 'newConfirmed', None, 'least')
    top_5_least_fatalities_str, top_5_least_fatalities_df = access.get_top_n_countries(5, 'newFatalities', None, 'least')
    total_confirmed_highest = access.get_top_n_countries(1, 'totalConfirmed', None, 'most')
    total_fatalities_highest = access.get_top_n_countries(1, 'totalFatalities', None, 'most')
    if err:
        return str(err)
    for user in user_list:
        email_string = """Hi here! It's Co!
        Here is your daily summary of global COVID-19 statistics for """
        email_string += str(today) + ': ' + '\n' + '\n'
        email = user['email']
        info_string = [email_string]
        # if user['record_confirmed']:
        #     info_string.append(record_confirmed)
        #     info_string.append('\n')
        # if user['record_fatalities']:
        #     info_string.append(record_fatalities)
        #     info_string.append('\n')
        if user['top_5_most_confirmed']:
            info_string.append(top_5_most_confirmed_str)
            info_string.append(top_5_most_confirmed_df)
            info_string.append('\n')
        if user['top_5_most_fatalities']:
            info_string.append(top_5_most_fatalities_str)
            info_string.append(top_5_most_fatalities_df)
            info_string.append('\n')
        if user['top_5_least_confirmed']:
            info_string.append(top_5_least_confirmed_str)
            info_string.append(top_5_least_confirmed_df)
            info_string.append('\n')
        if user['top_5_least_fatalities']:
            info_string.append(top_5_least_fatalities_str)
            info_string.append(top_5_least_fatalities_df)
            info_string.append('\n')
        if user['total_fatalities_highest']:
            info_string.append(total_fatalities_highest)
            info_string.append('\n')
        if user['total_confirmed_highest']:
            info_string.append(total_confirmed_highest)
            info_string.append('\n')
        info_string.append('Stay safe and healthy!')
        info_string.append(yagmail.inline('co1.png'))
        yag.send(email, 'Daily COVID-19 Report by Co', info_string)
def send_email_report(image_paths):
    """
    Sends an email report with the specified images embedded in the email. The function expects EMAIL_USERNAME,
    EMAIL_PASSWORD, and EMAIL_RECIPIENT environment variables.
    :param image_paths: Python list of image paths we want to include in the email
    """
    yag = yagmail.SMTP(os.environ['EMAIL_USERNAME'],
                       os.environ['EMAIL_PASSWORD'])
    recipient = os.environ['EMAIL_RECIPIENT']
    subject = 'COVID-19 Data Report for ' + str(TODAY)
    contents = ['<h3> COVID-19 charts with the latest data </h3>']
    for image in image_paths:
        inline_image = yagmail.inline(image)
        contents.append(inline_image)
    yag.send(to=recipient, subject=subject, contents=contents)
    def send_notification(self,
                          subject="OctoPrint notification",
                          body=[""],
                          snapshot=True,
                          event=""):

        # If a snapshot is requested, let's grab it now.
        if snapshot and not (event == "PrintStarted"):
            snapshot_url = self._settings.global_get(["webcam", "snapshot"])
            if snapshot_url:
                try:
                    try:
                        from urllib.parse import urlparse, urlencode
                        from urllib.request import urlretrieve, urlopen, Request
                        from urllib.error import HTTPError
                    except ImportError as e:
                        from urlparse import urlparse
                        from urllib import urlencode, urlretrieve
                        from urllib2 import urlopen, Request, HTTPError
                    filename, headers = urlretrieve(
                        snapshot_url,
                        tempfile.gettempdir() + "/snapshot.jpg")
                except Exception as e:
                    self._logger.exception(
                        "Snapshot error (sending email notification without image): %s"
                        % (str(e)))
                else:
                    body.append(yagmail.inline(filename))

        # Exceptions thrown by any of the following lines are intentionally not
        # caught. The callers need to be able to handle them in different ways.
        mailer = yagmail.SMTP(user={
            self._settings.get(['mail_username']):
            self._settings.get(['mail_useralias'])
        },
                              host=self._settings.get(['mail_server']),
                              port=self._settings.get(['mail_server_port']),
                              smtp_starttls=self._settings.get(
                                  ['mail_server_tls']),
                              smtp_ssl=self._settings.get(['mail_server_ssl']))
        emails = [
            email.strip()
            for email in self._settings.get(['recipient_address']).split(',')
        ]
        mailer.send(to=emails,
                    subject=subject,
                    contents=body,
                    headers={"Date": formatdate()})
Exemple #10
0
def ch_birth():
    x = date.today()
    f = 0
    for e in data["Birthdate"]:
        name = ()
        if e.month == x.month:
            if e.day == x.day:
                name = (data['Name'][f])
                email = (data['email_id'][f])
                print(name)
                contents = ("Happy Birthday {},".format(name), '\n',
                            Wishes[np.random.randint(0, 6)],
                            yagmail.inline("Stuff\B.jpg"))
                email_send(contents, email)

        f += 1
Exemple #11
0
    def send_fancy_email(self):
        sender_email = environ.get('MFM_email')
        sender_password = keyring.get_password('mfm', 'mfm')
        receiver_email = self.user_email
        subject = 'MFM App Report'

        body1 = f'<br><br><center>' \
            f'<h2><b>MyFinanceManager Weekly Report</b></h2>' \
            f'<h3><br>{self.df_assets(True)}</h3>' \
            f'</center>'

        img = self.graph(profit_numbers=True, save_only=True)

        body2 = f'<br><center>' \
            f'<h3><u>Portfolio History Stats</u></h3>' \
            f'{self.df_history(tabulate_mode=True, to_email=True)}</center>'

        body3 = f'<br><center>' \
            f'<h3><u>Current Holdings</u></h3>' \
            f'{self.df_stocks(to_email=True)}</center>' \
            f'<br><br><br><br><big>End of report.</big>' \
            f'<br><small>Sent by MyFinanceManager.</small>'

        contents = [body1, yagmail.inline(img), body2, body3]

        if self.days_left < 5 and self.days_left != 0:
            body_0 = f'<br><center><h4><u>Warning:</u><br>' \
                     f'{self.days_left} to update login password in trader site.</h4></center><br>'
            contents.insert(0, body_0)

        if self.trader_cf < 50:
            body_1 = f'<br><center><h4><u>Warning:</u><br>' \
                     f' Balance in trader is: {self.trader_cf},<br>' \
                     f' consider adding cash to trader balance.</h4></center><br>'
            contents.insert(0, body_1)

        try:
            self.LOG.debug('Trying to send fancy text email message')
            yag = yagmail.SMTP(sender_email, sender_password)
            yag.send(receiver_email, subject, contents)
            self.LOG.info(f'Email sent successfully to {receiver_email}')
            return True

        except Exception as e:
            self.LOG.exception('Error in sending plain text email message')
            raise e
Exemple #12
0
def txt_img_mail2wiz(txt_files,
                     mailhost,
                     mailuser,
                     mailpassword,
                     mailreceiver,
                     txt_only=False):
    """将文本或图片及对应OCR文本批量发送到为知笔记"""
    for num, txt_file in enumerate(txt_files, 1):
        print(f'正在处理第{num}个文件:{txt_file.name}……')
        email_content = []
        try:
            with open(txt_file, encoding='utf-8') as f:
                email_content.append(f.read())
        except Exception:
            with open(txt_file, encoding='gbk') as f:
                email_content.append(f.read())

        email_title = txt_file.stem.replace('#',
                                            '')  # 删除'#'标识,否则相关内容会被为知笔记识别为tag
        email_to = [mailreceiver]
        if not txt_only:
            image_file = txt_file.with_suffix('.jpg') if txt_file.with_suffix(
                '.jpg') else txt_file.with_suffix('.png')
            email_content.append(
                yagmail.inline(image_file))  # 图片嵌入邮件正文,而不是作为附件

        # 连接服务器,发送邮件
        yag_server = yagmail.SMTP(user=mailuser,
                                  password=mailpassword,
                                  host=mailhost)
        try:
            yag_server.send(email_to, email_title, email_content)
            # time.sleep(1)
            # 移动已处理文件到done文件夹
            if not pathlib.Path.exists(r'.\done'):
                pathlib.Path.mkdir(r'.\done')
            shutil.move(txt_file, '.\\done')
            if not txt_only:
                shutil.move(image_file, '.\\done')
        except Exception as e:
            print(e)
            # time.sleep(10)

        yag_server.close()
Exemple #13
0
def addDetails():
    data = request.form
    passw = data['Password']
    main_dir = os.getcwd()
    yagmail.register("*****@*****.**", passw)
    yag = yagmail.SMTP("*****@*****.**", passw)
    image_folder = os.path.join(main_dir,'images')
    template_folder = os.path.join(main_dir,'templates')
    html_msg = [yagmail.inline(os.path.join(image_folder,"profile2.jpg")),
    os.path.join(template_folder,"links.html"),
    main_dir + "/docs/Resume.pdf"]
    # Instantiate the Application object and execute required method.
    obj = Application(data)
    # Insert data
    obj.add_details()
    email = data['Email Address']
    """Send Email"""
    yag.send(email, obj.subject, html_msg)
    return render_template('user_form_response.html')
Exemple #14
0
    def sendemail(self,tweets):

        # Create list of strings of positive tweets
        body='Below positive tweets:'
        for tweet in [tweet for tweet in tweets if tweet['sentiment'] == 'positive']:
            # Convert to string and delete line break for better layout in email
            tweet = str(tweet['text']).replace("\n"," ")
            body += '\n {}' .format(tweet)

        # Create list of strings of negative tweets
        body +='\n \n Below negative tweets:'
        for tweet in [tweet for tweet in tweets if tweet['sentiment'] == 'negative']:
            tweet = str(tweet['text']).replace("\n"," ")
            body += '\n {}' .format(tweet)

        # Login to gmail account
        yag=yagmail.SMTP('*****@*****.**','yourgmailpassword')
        # Creating boyd of email with text and picture
        contents = [body, yagmail.inline("yourdpyfiledirectory")]
        # Send to email address
        yag.send('*****@*****.**', '5 sma has crossed 10 sma', contents)
    def send_notification(self,
                          subject="OctoPrint notification",
                          body=[""],
                          snapshot=True):

        # If a snapshot is requested, let's grab it now.
        if snapshot:
            snapshot_url = self._settings.global_get(["webcam", "snapshot"])
            if snapshot_url:
                try:
                    import urllib
                    filename, headers = urllib.urlretrieve(
                        snapshot_url,
                        tempfile.gettempdir() + "/snapshot.jpg")
                except Exception as e:
                    self._logger.exception(
                        "Snapshot error (sending email notification without image): %s"
                        % (str(e)))
                else:
                    body.append(yagmail.inline(filename))

        # Exceptions thrown by any of the following lines are intentionally not
        # caught. The callers need to be able to handle them in different ways.
        mailer = yagmail.SMTP(user={
            self._settings.get(['mail_username']):
            self._settings.get(['mail_useralias'])
        },
                              host=self._settings.get(['mail_server']))
        emails = [
            email.strip()
            for email in self._settings.get(['recipient_address']).split(',')
        ]
        mailer.send(to=emails,
                    subject=subject,
                    contents=body,
                    validate_email=False)
Exemple #16
0
import yagmail
import pymysql

yag = yagmail.SMTP(user='******',
                   password='******',
                   host='smtp.gmail.com')  #参数为发送邮箱, 邮箱密码(授权码), 发送邮箱服务器

#邮箱正文,是一个列表
contents = [
    "<h1 style='color:red'>一级标题</h1>",  #可以是html语言
    #'beauty.jpg',#可以是文件,以附件形式发送
    yagmail.inline('beauty.jpg'),  # 这样的话,图片会内嵌到正文
    'hello world',  #可以是普通文本
]

db = pymysql.connect('localhost', 'root', '897011805', 'yhj')
cursor = db.cursor()
sql = "select distinct email from newhaiwai limit 500"
cursor.execute(sql)
db.commit()
results = cursor.fetchall()
for row in results:
    fname = row[0]
    # lname = row[1]
    # age = row[2]
    # sex = row[3]
    # income = row[4]
    print('zzzzzzzzzzzzzzzzzzzzzzzzzzz', fname)
db.close()

yag.send(to='*****@*****.**', subject='test', contents=contents)
Exemple #17
0
                fp.writelines([i + "\n" for i in send_list])
            else:
                fp.write(send_list + "\n")


if __name__ == '__main__':
    import os
    from dotenv import load_dotenv

    load_dotenv()
    # 链接邮箱服务器
    yag = yagmail.SMTP(user=os.getenv("USER_NAME"),
                       password=os.getenv("USER_PWD"),
                       host='smtp.163.com')

    # 邮箱正文
    contents = [
        '这是一封正常邮件,需要测试',
        '这是一封正常邮件,需要测试1',
        '这是一封正常邮件,需要测试2',
        '这是一封正常邮件,需要测试3',
        '这是一封正常邮件,需要测试4',
        'You can find an audio file attached.',
        yagmail.inline("Snipaste_2020-03-16_16-44-15.png"),
        # "./Snipaste_2020-03-09_23-25-23.png",
    ]

    # 发送邮件
    yag.send(os.getenv("SEND_EMAIL"), '重要消息cc', contents)
    print("发送成功")
        'href': 'http://aaa.com/1/2/3.shtml'
    }, {
        'title': 'shanghia',
        'href': 'http://aaa.com/1/2/4.shtml'
    }, {
        'title': 'shenzhen',
        'href': 'http://aaa.com/1/2/5.shtml'
    }]
    # result = my_render('hzfc.html', items=links)
    result = my_render('hzfc.html', **locals())
    # print(result)
    return result


if __name__ == '__main__':
    with open(r'send_email\performance.html') as f:
        test = f.read()  # read html content
    r = test_html()  # read dynamic html content
    yag = yagmail.SMTP(user="******",
                       password='******',
                       host='smtp.qq.com')
    contents = [
        'this is a test',  # send string
        test,
        r,  # send html content
        yagmail.inline('iterator.png'),  # built-in picture
        'base.cfg'
    ]  # attachment
    yag.send(to='*****@*****.**',
             subject='SendHelloTest',
             contents=contents)
import yagmail
from datetime import date
import os
import time

current_dir = os.getcwd()
root_dir = os.path.dirname(current_dir)

output_dir = os.path.join(root_dir, 'output')
notebook_path = os.path.join(output_dir, "Nuove Case.pdf")

email_path = os.path.join(root_dir, "email_list/email_list.txt")

#import email_list
with open(email_path, 'r') as file:
    mail_list = file.read().splitlines()

print(f"Sending email... to {', '.join(mail_list)}\n")
today = date.today()

yag = yagmail.SMTP("*****@*****.**")

CONTENTS = [
    'Case nuove in zona Barona/Famagosta.',
    yagmail.inline(notebook_path)
]

for email in mail_list:
    yag.send(email, "Nuove Case", CONTENTS)
    time.sleep(3)
Exemple #20
0
 def make_pic_inline(self, pic_path):
     return yagmail.inline(pic_path)
Exemple #21
0
# import keyring
# keyring.set_password('yagmail','邮箱地址','SMTP码')

'''
发送邮件
'''

import yagmail

with yagmail.SMTP(user='******',host='邮箱的 smtp 网址') as yag:
    body = '正文内容'
    img = '图片文件路径'
    yag.send(to=['收件人邮箱地址'],cc=['抄送人邮箱地址'],bcc=['密送人邮箱地址']subject='主题',contents=[body,img,yagmail.inline('邮件内容中内嵌图片文件路径')],attachments=['附件文件路径'])
    print('发送成功!!')


'''
接收邮箱所有附件
'''

from imbox import Imbox

pwd = keyring.get_password('yagmail','邮箱地址')
with Imbox('邮箱的 imap 网址','邮箱地址',pwd,ssl=True) as imbox:
    all_inbox_messages = imbox.messages()
    for uid, message in all_inbox_messages:
        print(message.subject)
        print(message.body['plain'])

'''
message.sent_from 发件人
Exemple #22
0
import csv
from datetime import date
import yagmail

yag_smtp_connection = yagmail.SMTP(user="******",
                                   password="******",
                                   host='smtp.gmail.com')

today = date.today()
d1 = today.strftime("%d-%m")

f = open('BirthdayData.csv')
csv_f = csv.reader(f)

for row in csv_f:
    if row[0] == d1:
        print(row[1])
        print(row[2])
        subject = 'HAPPY BIRTHDAY'
        contents = """Happy Birthday %s,

We wish you a very much happy Birthday

""" % (row[1])
        image = [yagmail.inline(row[3])]
        yag_smtp_connection.send(row[2], subject, contents, image)
Exemple #23
0
                flag_img = 1
                break

        if flag_img:
            send_type = "img"
        else:
            send_type = "attachment"

    #print(send_type)
    #print(content_text)

    if send_type == "text":
        contents = [content_text]

    if send_type == "img":
        contents = [content_text, yagmail.inline(sys.argv[1 + argc_r0])]

    if send_type == "attachment":
        contents = [content_text, sys.argv[1 + argc_r0]]

    sub_content = "jd_send_by_ygmail: "
    content_text_no_line_LF = get_subject(content_text)
    MAX_LEN = 25
    if len(content_text_no_line_LF) > MAX_LEN:
        sub_content = sub_content + content_text_no_line_LF[0:MAX_LEN] + " ..."
    else:
        sub_content = sub_content + content_text_no_line_LF

    print("- from\t: " + user_mail_addr)
    print("- to\t: " + to_mail_addr)
    print("- content_text\t: " + "\n" + "======")
Exemple #24
0
def yagmail_test(to_address, msg_body, image_path):
    yag = yagmail.SMTP(USERNAME, PASSWORD)
    #yag.send(to_address, contents=[yagmail.inline("someimg.png"), "<h1>This is a test</h1>","This is some text as well"])
    yag.send(to_address,
             contents=[yagmail.inline(image_path), "<h1>This is a test</h1>", "This is some text as well"])
# Html Content
html_content = '''
<html>
    <body>
    <img src='img1.png'>
    <a href='https://www.google.com'>Google</a>
    </body>
</html>
'''
message = MIMEMultipart('alternative')
content = MIMEText(html_content, 'html')
message.attach(content)

yag = yagmail.SMTP(user=sender_mail, password=password)
contents = [yagmail.inline('img1.png'),'Dear Sir/Mam,','Greetings from Pap-Tech Engineers & Associates!',\
'\n','We would like to introduce ourselves 30 year experience as a Designer',\
'\n','Manufacturer and Supplier of Quality Testing Equipment.',\
'\n','\tOur CEO/Paper Technologist Mr. V.K. Agarwal passed out from IIT-Roorkee 1987 batch do all types of consultancy related to Pulp,Paper and Converting Mills.',\
'\n','We Design, Manufacture & supply the followings with Calibration & Repairing services: -',\
 '1.Quality Lab Testing Equipments used in Pulp, Paper, Printing, Packaging, Converting, Adhesives, Chemicals and others.',\
 '2.Calibration & Repairing Services.',\
 '3.AMC Services.',\
 '4. Spare Parts of Testing Equipment i.e. Aluminum Foil & Diaphragm Etc.',\
 '\n','For more information on our products & our company, kindly visit our websites given below .We are enclosing our Product Catalogue with this letter.',\
 '\n','As we are very much interested to do business with you on a long term basis, we request you to please enlist our name in your approved vendor list and send us your valued purchase inquiries from time to time so as to enable us to quote our most competitive rates and terms.',\
 '\n','We would like to welcome the queries from your end. Feel free to have any communication in this regard with us.','\n',\
 '\n','Looking forward for a business association. ','img1.png','img2.jpg','img3.jpg','img4.jpg','img5.jpg','Profile.pdf']

yag.send('*****@*****.**', subject, contents)