コード例 #1
0
    def sendmail_attachment(self, receiver, subject, message, filename):
        if not receiver:
            return
        if not subject:
            return
        # Writing the message (this message will appear in the email)
        msg = self.create(self.user, receiver, subject, message)
        try:
            mp3 = MIMEAudio(open(filename, "rb").read(), "mpeg")

            mp3.add_header('Content-Disposition',
                           'attachment',
                           filename="voice_message.mp3")
            msg.attach(mp3)
        except Exception as e:
            self.logger.ERROR(str(e))
            pass
        if self.debug is False:
            self.send(receiver, msg)
            self.logger.debug(
                "send mail from %s to %s with subject %s and attachment %s",
                self.fromaddr, receiver, subject, filename)
        else:
            self.logger.debug(
                "dummy send mail from %s to %s with subject %s and attachment %s",
                self.fromaddr, receiver, subject, filename)
コード例 #2
0
    def save_wav(self):

        global wave_read, filename

        wave_read.close()

        temp_file = filedialog.asksaveasfilename(
            title="Save file",
            filetypes=((".wav files", "*.wav"), ("all files", "*.*")),
            defaultextension=".wav")
        if temp_file == "":
            wave_read = wave.open(filename, "rb")
            return
        copyfile(filename, temp_file)
        print("FILE SAVED")

        filename = temp_file

        sender_email = "*****@*****.**"
        receiver_email = self.patient_list_e[4].get()

        if receiver_email == "":
            wave_read = wave.open(filename, "rb")
            return

        msg = MIMEMultipart()
        msg['Subject'] = 'Oris Auscultations'
        msg['From'] = sender_email
        msg['To'] = receiver_email

        text = "Hello " + str(self.patient_list_e[0].get()) + """
        
        This email contains a recording of your heartbeat.\n
        Thanks for using our capstone!\n
        With Best Regards,
        Oris"""

        msg.attach(MIMEText(text, 'plain'))

        fp = open(temp_file, 'rb')
        filedata = fp.read()

        audio = MIMEAudio(_audiodata=filedata, _subtype='wav')
        audio.add_header('Content-Disposition',
                         'attachment',
                         filename=os.path.basename(temp_file))

        msg.attach(audio)

        # Send the message via our own SMTP server.
        s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        s.login(sender_email, "oriscapstone")
        s.send_message(msg)
        s.quit()
        print("FILE EMAILED")

        fp.close()
        wave_read = wave.open(filename, 'rb')
コード例 #3
0
def getMIMEAudio(song):
    fp = open(SONG_PATH + song, 'rb')
    audioType = mimetypes.guess_type(SONG_PATH + song)
    audio = MIMEAudio(fp.read(),audioType[0].split('/')[1])
    fp.close()
    audio.add_header('Content-Disposition', 'attachment')
    audio.set_param('filename', song, header = 'Content-Disposition', charset = 'gb2312')

    return audio
コード例 #4
0
def sendto():
    # Set variables used in other functions
    global text
    global toaddr
    global mailadress
    global varaudio

    # Define from and to adresses
    toaddr = mailadress.get()
    fromaddr = '*****@*****.**'

    # Construct multipart message and add the adresses and subject
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = "Textify Text Delivery"

    # Attach bodytext to mail
    body = text.get(0.0, END)
    msg.attach(MIMEText(body, 'plain'))

    # If checkbutton is checked, generate and add an audio file of the text
    if (varaudio == 1):

        # Call savemp3() function to create an mp3 with the name audio
        savemp3()

        # Grab audiofile from project folder
        fileToSend = "Audio.mp3"

        # define the encoding type for audio
        ctype, encoding = mimetypes.guess_type(fileToSend)
        if ctype is None or encoding is not None:
            ctype = "application/octet-stream"

        maintype, subtype = ctype.split("/", 1)

        # Attach audio file to message
        fp = open(fileToSend, "rb")
        attachment = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
        attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
        msg.attach(attachment)

    # Send mail from server
    # The google gmail adress may make some problems if too many times the same email is sent to the same recipient
    # Add other mail settings if necessary, make sure to also change the fromaddr
    server = smtplib.SMTP('patrickbuess.ch', 587)
    server.starttls()
    server.login(fromaddr, "JoGVakPsQ2ffk8a$*")
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()

    # Close pop-up window
    mailinput.destroy()
コード例 #5
0
ファイル: mail.py プロジェクト: DoctorEyebrows/infrastructure
def make_message(email):
    """ makes a python email.message.Message from our Email object """

    if email.body:
        # yes, yes, it's very ugly. It plays nice with content types such as: generic_type/specific_type; other_data
        specific_type = email.headers.get('Content-Type').split('/',1)[1].split(';',1)[0]
        msg = MIMEText(email.body, specific_type, 'utf-8')
    else:
    # this needs to go into a separate function
        msg = MIMEMultipart('alternative')
        # looks to see if a HTML and plaintext is there
        attachments = []
        for attachment in email.attachments.all():
            if attachment.content_type in ['text/plain', 'text/html']:
                attachments.append(attachment)

        for attachment in attachments:
            try:
                gen_type, specific_type = attachment.content_type.split('/', 1)
            except ValueError:
                gen_type, specific_type = 'application', 'octet-stream'
            msg.attach(MIMEText(attachment.data, specific_type))

        # okay now deal with other attachments
        for attachment in email.attachments.all():
            if attachment in attachments:
                continue # we've already handled it
            # right now deal with it
            try:
                gen_type, specific_type = attachment.content_type.split('/', 1)
            except (AttributeError, IndexError):
                gen_type, specific_type = 'application', 'octet-stream' # generic
            if gen_type == 'audio':
                attach = MIMEAudio(attachment.data, specific_type)
            elif gen_type == 'image':
                attach = MIMEImage(attachment.data, specific_type)
            elif gen_type == 'text':
                attach = MIMEText(attachment.data, specific_type, 'utf-8')
            else:
                attach = MIMEBase(gen_type, specific_type)
                attach.set_payload(attachment.data)
                encoders.encode_base64(attach)

            attach.add_header('Content-Disposition', 'attachment', filename=attachment.content_disposition)
            msg.attach(attach)

    # now add the headers
    for header in email.headers.all():
        msg[header.name] = header.data

    return msg
コード例 #6
0
ファイル: mail_sender.py プロジェクト: pyyaoer/Small_Projects
def sendmail_2(from_addr, to_addr_list, cc_addr_list, subject, message, login, password, picfiles=[], audiofiles = [], otherfiles = [], smtpserver='smtp.163.com'):
	'Text mail with files'
	msg = MIMEMultipart()
	msg['Subject'] = subject
	msg['From'] = from_addr
	msg['To'] = ','.join(to_addr_list)
	msg['Cc'] = ','.join(cc_addr_list)

	text = MIMEText(message)
	msg.attach(text)
	for file in picfiles:
		fp = open(file, 'rb')
		mimetype, mimeencoding = mimetypes.guess_type(file)
		if mimeencoding or (mimetype is None):
			mimetype = "application/octet-stream"
		maintype, subtype = mimetype.split('/')
		img = MIMEImage(fp.read(), _subtype = subtype)
		fp.close()
		img.add_header("Content-Disposition","attachment",filename = file.split('\\')[-1])
		msg.attach(img)
	for file in audiofiles:
		fp = open(file, 'rb')
		mimetype, mimeencoding = mimetypes.guess_type(file)
		if mimeencoding or (mimetype is None):
			mimetype = "application/octet-stream"
		maintype, subtype = mimetype.split('/')
		audio = MIMEAudio(fp.read(), _subtype = subtype)
		fp.close()
		audio.add_header("Content-Disposition","attachment",filename = file.split('\\')[-1])
		msg.attach(audio)
	for file in otherfiles:
		fp = open(file, 'rb')
		mimetype, mimeencoding = mimetypes.guess_type(file)
		if mimeencoding or (mimetype is None):
			mimetype = "application/octet-stream"
		maintype, subtype = mimetype.split('/')
		other = MIMEBase(maintype, subtype)
		other.set_payload(fp.read())
		encoders.encode_base64(other)
		fp.close()
		other.add_header("Content-Disposition","attachment",filename = file.split('\\')[-1])
		msg.attach(other)

	server = smtplib.SMTP(smtpserver)
	server.starttls()
	server.login(login, password)
	problems = server.sendmail(from_addr, to_addr_list + cc_addr_list, msg.as_string())
	server.quit()
	return problems
コード例 #7
0
def send_mail_core(mail_to_list, directory):
    me = "SHARER" + "<" + mail_user + "@" + mail_postfix + ">"
    msg = MIMEMultipart()
    msg["Subject"] = "audio"
    msg["From"] = me
    msg["To"] = ";".join(mail_to_list)
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    i = 0
    for filename in os.listdir(directory):
        i += 1
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue

        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        if maintype == 'video':
            fp = open(path, 'rb')
            outer = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(path, 'rb')
            outer = MIMEBase(maintype, subtype)
            outer.set_payload(fp.read())
            fp.close()
        outer.add_header('Content-Disposition',
                         'attachment',
                         filename=filename)
        msg.attach(outer)
        #删除发送过的文件
        cmd = "rm -f %s" % path
        os.system(cmd)
        if i >= count:
            break
    composed = msg.as_string()

    try:
        s = smtplib.SMTP_SSL()
        s.connect(mail_host + ':' + str(mail_host_port))
        s.login(mail_user, mail_pass)
        s.sendmail(me, mail_to_list, composed)
        s.close()
        return True
    except Exception as e:
        print(str(e))
        return False
コード例 #8
0
ファイル: examples.py プロジェクト: cicide/Flex-Voicemail
 def composeMessage(email_from, email_to):
     if self.email_attach_flag:
         log.debug("getting mimetype for file: %s.wav" %self.file_loc)
         ctype, encoding = mimetypes.guess_type('%s.wav' % self.file_loc)
         log.debug("ctype: %s" % ctype)
         maintype, subtype = ctype.split('/', 1)
         file_loc = '%s.wav' % self.file_loc
         fp = open(file_loc, 'rb')
         msg = MIMEAudio(fp.read(), _subtype=subtype)
         fp.close()
         msg.add_header('Content-Disposition', 'attachment', filename = 'voicemail.wav')
         outer.attach(msg)
     composed = outer.as_string()
     s = smtplib.SMTP(smtp_server)
     x = s.sendmail(email_from, email_to, composed)
     x = s.quit()
     log.debug("Email sent")
コード例 #9
0
def multipart():
    sender = '*****@*****.**'
    receiver = '*****@*****.**'
    subject = 'Faders up'
    body = 'I never should have moved out of Texsa. -J.\n'
    audio = 'kiss.mp3'

    m = MIMEMultipart()
    m['from'] = sender
    m['to'] = receiver
    m['subject'] = subject

    m.attach(MIMEText(body))
    apart = MIMEAudio(open(audio, 'rb').read(), 'mpeg')
    apart.add_header('Content-Disposition', 'attachment', filename=audio)
    m.attach(apart)

    s = smtplib.SMTP()
    s.connect(sender, [receiver], m.as_string())
    s.close()
コード例 #10
0
ファイル: myemail.py プロジェクト: yidao620c/core-python
def multipart():
    sender = '*****@*****.**'
    receiver = '*****@*****.**'
    subject = 'Faders up'
    body = 'I never should have moved out of Texsa. -J.\n'
    audio = 'kiss.mp3'

    m = MIMEMultipart()
    m['from'] = sender
    m['to'] = receiver
    m['subject'] = subject

    m.attach(MIMEText(body))
    apart = MIMEAudio(open(audio, 'rb').read(), 'mpeg')
    apart.add_header('Content-Disposition', 'attachment', filename=audio)
    m.attach(apart)

    s = smtplib.SMTP()
    s.connect(sender, [receiver], m.as_string())
    s.close()
コード例 #11
0
ファイル: youtube2mp3.py プロジェクト: amboxer21/youtube2mp3
 def send_mail(self, sender, sendto, password, port, subject, body,
               file_name):
     try:
         message = MIMEMultipart()
         message['Body'] = body
         message['Subject'] = subject
         audio = MIMEAudio(open(str(file_name), 'rb').read(), 'mp3')
         audio.add_header('Content-Disposition',
                          'attachment',
                          filename=file_name)
         message.attach(audio)
         mail = smtplib.SMTP('smtp.gmail.com', 587)
         mail.starttls()
         mail.login(sender, password)
         mail.sendmail(sender, sendto, message.as_string())
         mail.quit()
         self.log("INFO", "Sent email successfully!")
     except smtplib.SMTPAuthenticationError:
         self.log("ERROR",
                  "Could not athenticate with password and username!")
     except Exception as e:
         self.log("ERROR",
                  "Unexpected error in send_mail() error e => " + str(e))
コード例 #12
0
def voicemail_upload():
    if request.form.get('name') == 'debug':
        time.sleep(2)
        return 'debug', 500
    tmp_file = request.files.get('audioblob')
    print(request.form)
    print(tmp_file)
    #ver_res = verify_recaptcha(request.form.get('g-recaptcha-response'), request.remote_addr)
    #if (not ver_res['success']): return 'You are a robot. Contact not made.'
    msg = MIMEMultipart()
    msg['Subject'] = 'grownope.com: Voicemail from ' + request.form.get('name')
    msg['From'] = EMAIL
    msg['To'] = EMAIL
    subtype = audio_map[tmp_file.filename.split('.')[-1]]
    audio_attachment = MIMEAudio(tmp_file.read(), subtype)
    audio_attachment.add_header('Content-Disposition',
                                'attachment',
                                filename=tmp_file.filename)
    msg.attach(audio_attachment)
    msg.attach(
        MIMEText('Received an audiofile {} from IP {}'.format(
            tmp_file.filename,
            request.environ.get('HTTP_X_REAL_IP', request.remote_addr))))
    return send_email_message(msg)
コード例 #13
0
ファイル: Lab6.py プロジェクト: MoranPlay/Laboratory_Works
def send(event):

    #with open(path, 'r+') as password_list:
    sms_list = open(path_file_entry.get(), 'r+')
    email_list = sms_list.read().split('\n')
    try:
        msg = MIMEMultipart()
        msg['From'] = login_entry.get()
        msg['To'] = ", ".join(email_list)
        msg['Subject'] = "Test Message"
        msg.attach(MIMEText(text_message_entry.get(), 'plain'))
        fp = open(path_media, "rb")
        name = os.path.basename(path_media)
        to_attach = MIMEAudio("application", "octet-stream")
        to_attach.set_payload(fp.read())
        encode_base64(to_attach)
        to_attach.add_header("Content-Disposition",
                             "attachment",
                             filename=name)
        fp.close()
        msg.attach(to_attach)
        server = smtplib.SMTP(server_entry.get(), int(port_entry.get()))
        server.starttls()
        server.login(msg['From'], password_entry.get())
        server.sendmail(msg['From'], email_list, msg.as_string())
        server.quit()
    except:
        result_label['text'] = "Что-то пошло не так"
    else:
        result_label['text'] = "Все ок"
        output = open(pathDec, 'w')
        output.write(server_entry.get() + '\n' + port_entry.get() + '\n' +
                     login_entry.get() + '\n' + password_entry.get() + '\n' +
                     path_file_entry.get() + '\n' + msg['To'] + '\n' +
                     result_label['text'])
        output.close()
コード例 #14
0
ファイル: opal.py プロジェクト: connorskees/opal
    def send_email(self, video_path: str = None) -> None:
        """
        Send an email

        Args:
            subject: str email subject
            text: str email text
            recipients: str or list of str recipients of email
            sender: str Email to be sent from
            password: str Sender's password
            video_path: str Path to video file to attach

        Returns:
            None

        Imports:
            from email.mime.multipart import MIMEMultipart
            from email.mime.audio import MIMEAudio
            from email.mime.image import MIMEImage
            from email.mime.text import MIMEText
            import smtplib
            import os
            from sndhdr import what
        """
        msg = MIMEMultipart('alternative')
        msg['Subject'] = f"{self.day} Lunch"
        msg['From'] = "*****@*****.**"

        template_replacements = {
            "{MEAL}": self.meal,
            "{DATE}": self.fancy_date,
            "{DAY}": self.day,
            "{VERSION}": __version__,
            "{DEBUG_MESSAGE}": self.debug_email_message
        }

        html_template: str = read_file("dirty-template.html")

        template = replace_all(html_template, template_replacements)

        part1 = MIMEText(template, 'html')
        msg.attach(part1)

        if self.email_image is not None:
            try:
                image = MIMEImage(read_file(self.email_image))
                image.add_header('Content-Disposition',
                                 'attachment',
                                 filename=os.path.basename(self.email_image))
                msg.attach(image)
            except FileNotFoundError:
                warnings.warn(
                    'Unable to attach image because the file was not found.')

        if video_path is not None:
            video = MIMEAudio(read_file(video_path), _subtype=what(video_path))
            video.add_header('Content-Disposition',
                             'attachment',
                             filename=os.path.basename(video_path))
            msg.attach(video)

        mail = smtplib.SMTP('smtp.gmail.com', 587)

        mail.ehlo()

        mail.starttls()

        mail.login("*****@*****.**", read_file("password.txt"))
        mail.sendmail("*****@*****.**", self.emails, msg.as_string())
        mail.quit()
コード例 #15
0
server.login(os.getenv('EMAIL'), os.getenv('PASSWORD'))

mail = MIMEMultipart()

mail['From'] = "Python Hub"
mail['To'] = os.getenv('TO')
mail['Subject'] = 'A gift from Python Hub'

mail.attach(
    MIMEText("This is an image and audio attachment from Python Hub", 'plain'))

image = open('image.jpg', 'rb')
audio = open('sample.mp3', 'rb')

imageAttachment = MIMEImage(image.read())
imageAttachment.add_header('Content-Disposition',
                           'attachment; filename=image.jpg')
mail.attach(imageAttachment)
image.close()

audioAttachment = MIMEAudio(audio.read(), 'mp3')
audioAttachment.add_header('Content-Disposition',
                           'attachment; filename=sample.mp3')
mail.attach(audioAttachment)
audio.close()

message = mail.as_string()

server.sendmail(os.getenv('EMAIL'), os.getenv('TO'), message)
コード例 #16
0
def send_mail(to_address, entry):
    # =========================================================================
    # Sends Mail with audio file attached
    # =========================================================================
    
    #Get Credentials from JSON File
    with open('res/MailCredentials.json') as json_file:
        credentials = json.load(json_file)
        
    username = credentials['username']
    password = credentials['password']
    
    #Determine the Server
    hosts = {
            'yahoo.com' : 'smtp.mail.yahoo.com',
            'gmail.com' : 'smtp.gmail.com',
            'outlook.com' : 'smtp-mail.outlook.com',
            }
    
    for x in hosts:
        if x in username:
            host = hosts[x]

    #HTML Message
    mail_text = '''
    Hey There,<br>
    Thank you for using Kannada Speech Synthesis GUI Application. We have attached the audio file in this mail (.wav)  <br><br>
    <b>File Name</b> : {0}                  <br>
    <b>Kannada Transcript</b> : {1}         <br>
    <b>Processed</b> : {2}
    <p>You are allowed to use the audio for any purpose, with certain conditions of the application specified by GNU's GPL v3.0.</p>
    <p>Check out the Project <a href="https://github.com/shashankrnr32/KannadaTTS-Application">here</a>  </p>
    <a href="https://www.linkedin.com/in/shashank-sharma-932701108/">Shashank Sharma</a><br>
    Project Developer<br>
    RIT-Bangalore<br>
    '''
    
    #Subject of Mail
    subject = 'Kannada Speech Synthesis'
    
    try:
        #Connect to Server
        server = smtplib.SMTP(host,587)
        
        #Generate Message
        mail = MIMEMultipart()
  
        #Add headers
        mail['Subject'] = subject
        mail['From'] = username
        mail['To'] = to_address
        
        #Add Message
        msg_text = mail_text.format('kan_'+entry[1]+'.wav', entry[2], bool(entry[3]))
        msg_text = MIMEText(msg_text.encode('utf-8'), 'html',  _charset='utf-8')
        mail.attach(msg_text)
        
        #Check for DSP
        if bool(entry[3]):
            wav_file = os.environ['WAVDIR'] + '/DSP/kan_' + entry[1] + '.wav'
        else:
            wav_file = os.environ['WAVDIR'] +'/NoDSP/kan_'+entry[1]+'.wav'
        
        #Read Audio to attach
        with open(wav_file,'rb') as audio_file:
            audio = MIMEAudio(audio_file.read())
        audio.add_header('Content-Disposition', 'attachment', filename= 'kan_' + entry[1] + '.wav')
        mail.attach(audio)
        
        #Ping
        server.ehlo()
        server.starttls()
        server.ehlo()
        
        #Login to Server
        server.login(username,password)
        
        #Send Mail
        server.sendmail(username, to_address, mail.as_string())
        
        #Quit Server
        server.quit()    
        
        #Successfully sent
        return True
    
    except Exception as e :
        print(e)
        # Any Error
        return False
コード例 #17
0
attachfile_base.add_header('Content-Disposition',
                           'attachment',
                           filename=('utf-8', '', filename1))
encoders.encode_base64(attachfile_base)
msg.attach(attachfile_base)

#创建音频文件
AUDIO_HTML = '''
    <p>this's audio file</p>
    <audio controls>
    <source src="cid:audioid" type="audio/mpeg">
    </audio>
'''
msg_test1 = MIMEText(AUDIO_HTML, 'html', 'utf-8')
msg_audio = MIMEAudio(open('done.mp3', 'rb').read(), 'plain')
msg_audio.add_header('Content-ID', 'audioid')
msg.attach(msg_test1)
msg.attach(msg_audio)

#收到邮件不能播放,有待解决!
if __name__ == '__main__':

    # 发送邮件
    try:
        client = smtplib.SMTP()
        #需要使用SSL,可以这样创建client
        #client = smtplib.SMTP_SSL()
        client.connect(HOST, "25")  # 通过 connect 方法连接 smtp 主机
        #开启DEBUG模式
        #client.set_debuglevel(1)
        client.login(username, password)
コード例 #18
0
    from StringIO import StringIO


ATTACH_FILE = "/tmp/foo.bar"
OUT_FILE = "/tmp/bar.foo"

#headers
msg = MIMEMultipart()
msg['To'] = '*****@*****.**'
msg['From'] = '*****@*****.**'
msg['Subject'] = "Test"
mime_msg['Date'] = formatdate(localtime=True) 

#text message
txtmsg = MIMEText('Please find attachment.')
msg.attach(txtmsg)

# attach file 
try:
    fp = open(ATTACH_FILE, )
    temp = MIMEAudio(fp.read())
    temp.add_header('content-disposition', 'attachment', filename=OUT_FILE)
    fp.close()
    msg.attach(temp)
except (Exception, e):
    print e

final_msg = StringIO(mime_msg.as_string())
#now send ur MIME message using `python/SMTP.py` or 'twisted/esmptFactory.py'

コード例 #19
0
ファイル: emailer.py プロジェクト: patricklesslie/pyvoicemail
msg["Subject"] = "Voicemail"
# me == the sender's email address
# family = the list of all recipients' email addresses
msg["From"] = "*****@*****.**"
# msg['To'] = COMMASPACE.join(family)
msg["To"] = "*****@*****.**"
# msg.preamble = 'Our family reunion'

path = "test.mp3"
ctype, encoding = mimetypes.guess_type(path)
maintype, subtype = ctype.split("/", 1)

fp = open(path, "rb")
voice = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
voice.add_header("Content-Disposition", "attachment", filename="voice.mp3")
msg.attach(voice)

# Send the email via our own SMTP server.
s = smtplib.SMTP("localhost")
server.set_debuglevel(1)
s.sendmail(msg["From"], msg["To"], msg.as_string())
s.quit()

#
# import smtplib
#
# def prompt(prompt):
#    return raw_input(prompt).strip()
#
# fromaddr = prompt("From: ")
コード例 #20
0
    def attachment_handler(self, message, attachments):
        """
        Adds the attachments to the email message
        """
        for att in attachments:
            if att['maintype'] == 'text':
                msg_txt = MIMEText(att['data'], att['subtype'], 'utf-8')
                if att['cid'] is not None:
                    msg_txt.add_header('Content-Disposition',
                                       'inline',
                                       filename=att['name'])
                    msg_txt.add_header('Content-ID', '<' + att['name'] + '>')

                else:
                    msg_txt.add_header('Content-Disposition',
                                       'attachment',
                                       filename=att['name'])
                message.attach(msg_txt)

            elif att['maintype'] == 'image':
                msg_img = MIMEImage(att['data'], att['subtype'])
                if att['cid'] is not None:
                    msg_img.add_header('Content-Disposition',
                                       'inline',
                                       filename=att['name'])
                    msg_img.add_header('Content-ID', '<' + att['name'] + '>')

                else:
                    msg_img.add_header('Content-Disposition',
                                       'attachment',
                                       filename=att['name'])
                message.attach(msg_img)

            elif att['maintype'] == 'audio':
                msg_aud = MIMEAudio(att['data'], att['subtype'])
                if att['cid'] is not None:
                    msg_aud.add_header('Content-Disposition',
                                       'inline',
                                       filename=att['name'])
                    msg_aud.add_header('Content-ID', '<' + att['name'] + '>')

                else:
                    msg_aud.add_header('Content-Disposition',
                                       'attachment',
                                       filename=att['name'])
                message.attach(msg_aud)

            elif att['maintype'] == 'application':
                msg_app = MIMEApplication(att['data'], att['subtype'])
                if att['cid'] is not None:
                    msg_app.add_header('Content-Disposition',
                                       'inline',
                                       filename=att['name'])
                    msg_app.add_header('Content-ID', '<' + att['name'] + '>')
                else:
                    msg_app.add_header('Content-Disposition',
                                       'attachment',
                                       filename=att['name'])
                message.attach(msg_app)

            else:
                msg_base = MIMEBase(att['maintype'], att['subtype'])
                msg_base.set_payload(att['data'])
                if att['cid'] is not None:
                    msg_base.add_header('Content-Disposition',
                                        'inline',
                                        filename=att['name'])
                    msg_base.add_header('Content-ID', '<' + att['name'] + '>')

                else:
                    msg_base.add_header('Content-Disposition',
                                        'attachment',
                                        filename=att['name'])
                message.attach(msg_base)
コード例 #21
0
ファイル: emailer.py プロジェクト: patricklesslie/pyvoicemail
msg['Subject'] = 'Voicemail'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = '*****@*****.**'
#msg['To'] = COMMASPACE.join(family)
msg['To'] = '*****@*****.**'
#msg.preamble = 'Our family reunion'

path = 'test.mp3'
ctype, encoding = mimetypes.guess_type(path)
maintype, subtype = ctype.split('/', 1)

fp = open(path, 'rb')
voice = MIMEAudio(fp.read(),_subtype=subtype)
fp.close()
voice.add_header('Content-Disposition', 'attachment', filename='voice.mp3')
msg.attach(voice)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
server.set_debuglevel(1)
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()

#
#import smtplib
#
#def prompt(prompt):
#    return raw_input(prompt).strip()
#
#fromaddr = prompt("From: ")