Add attachment to the main mail
165613
public function send()
    {
        $vars = $this->templateContainer->getTemplateVars();
        $this->checkInvoice($vars);

        parent::send();
    }
5628
public function add() {
		$this->err('Queue Email Task cannot be added via Console.');
		$this->out('Please use createJob() on the QueuedTask Model to create a Proper Email Task.');
		$this->out('The Data Array should look something like this:');
		$this->out(var_export([
			'settings' => [
				'to' => 'email@example.com',
				'subject' => 'Email Subject',
				'from' => 'system@example.com',
				'template' => 'sometemplate',
			],
			'content' => 'hello world',
		], true));
		$this->out('Alternativly, you can pass the whole EmailLib to directly use it.');
	}
1036875
private function attachFiles(){
        if (count($this->attachments) === 0) {
            return;
        }
        // Get old message parts
        $mimeMessage = $this->message->getBody();
        if (is_string($mimeMessage)) {
            $originalBodyPart = new Mime\Part($mimeMessage);
            $originalBodyPart->type = $mimeMessage != strip_tags($mimeMessage)
                ? Mime\Mime::TYPE_HTML
                : Mime\Mime::TYPE_TEXT;
            // A Mime\Part body will be wraped into a Mime\Message, ensuring we handle a Mime\Message after this point
            $this->setBody($originalBodyPart);
            $mimeMessage = $this->message->getBody();;
        }
        $oldParts = $mimeMessage->getParts();
        // Generate a new Mime\Part for each attachment
        $attachmentParts    = [];
        $info               = new \finfo(FILEINFO_MIME_TYPE);
        foreach ($this->attachments as $key => $attachment) {
            if (! is_file($attachment)) {
                continue; // If checked file is not valid, continue to the next
            }
            // If the key is a string, use it as the attachment name
            $basename = is_string($key) ? $key : basename($attachment);
            $part               = new Mime\Part(fopen($attachment, 'r'));
            $part->id           = $basename;
            $part->filename     = $basename;
            $part->type         = $info->file($attachment);
            $part->encoding     = Mime\Mime::ENCODING_BASE64;
            $part->disposition  = Mime\Mime::DISPOSITION_ATTACHMENT;
            $attachmentParts[]  = $part;
        }
        $body = new Mime\Message();
        $body->setParts(array_merge($oldParts, $attachmentParts));
        $this->message->setBody($body);
    }
917430
public function saveAttachments($mail)
    {
        /** @var \Shockwavemk\Mail\Base\Model\Mail\Attachment[] $attachments */
        $attachments = $mail->getAttachments();

        foreach ($attachments as $attachment) {
            $this->saveAttachment($attachment);
        }

        return $this;
    }
929025
public function attachments()
    {
        $files = func_get_args();

        foreach ($files as $file) {
            if (is_string($file)) {
                $this->_attachments[] = ['file' => $file];
            } elseif (is_array($file)) {
                foreach ($file as $key => $value) {
                    $this->_attachments[] = ['name' => $key, 'file' => $value];
                }
            }
        }

        return $this;
    }
827089
def addAttachment(self, oid, file_path):
        
        if self.hasAttachments == True:
            attachURL = self._url + "/%s/addAttachment" % oid
            params = {'f':'json'}
            parsed = urlparse.urlparse(attachURL)

            files = {'attachment': file_path}
            res = self._post(url=attachURL,
                             param_dict=params,
                             files=files,
                             securityHandler=self._securityHandler,
                             proxy_port=self._proxy_port,
                             proxy_url=self._proxy_url)
            return self._unicode_convert(res)
        else:
            return "Attachments are not supported for this feature service."
150768
def insert_attachments(self, volumeID, attachments):
        '''  '''
        log.debug("adding new attachments to volume '{}': {}".format(volumeID, attachments))
        if not attachments:
            return
        rawVolume = self._req_raw_volume(volumeID)
        attsID = list()
        for index, a in enumerate(attachments):
            try:
                rawAttachment = self._assemble_attachment(a['file'], a)
                rawVolume['_source']['_attachments'].append(rawAttachment)
                attsID.append(rawAttachment['id'])
            except Exception:
                log.exception("Error while elaborating attachments array at index: {}".format(index))
                raise
        self._db.modify_book(volumeID, rawVolume['_source'], version=rawVolume['_version'])
        return attsID
222435
def attachment_upload(instance, filename):
    """"""
    return 'attachments/{app}_{model}/{pk}/{filename}'.format(
        app=instance.content_object._meta.app_label,
        model=instance.content_object._meta.object_name.lower(),
        pk=instance.content_object.pk,
        filename=filename,
    )
25769
def _make_attachment(self, attachment, str_encoding=None):
        
        is_inline_image = False
        if isinstance(attachment, MIMEBase):
            name = attachment.get_filename()
            content = attachment.get_payload(decode=True)
            mimetype = attachment.get_content_type()

            if attachment.get_content_maintype() == 'image' and attachment['Content-ID'] is not None:
                is_inline_image = True
                name = attachment['Content-ID']
        else:
            (name, content, mimetype) = attachment

        # Guess missing mimetype from filename, borrowed from
        # django.core.mail.EmailMessage._create_attachment()
        if mimetype is None and name is not None:
            mimetype, _ = mimetypes.guess_type(name)
        if mimetype is None:
            mimetype = DEFAULT_ATTACHMENT_MIME_TYPE

        try:
            # noinspection PyUnresolvedReferences
            if isinstance(content, unicode):
                # Python 2.x unicode string
                content = content.encode(str_encoding)
        except NameError:
            # Python 3 doesn't differentiate between strings and unicode
            # Convert python3 unicode str to bytes attachment:
            if isinstance(content, str):
                content = content.encode(str_encoding)

        content_b64 = b64encode(content)

        mj_attachment = {
            'Content-type': mimetype,
            'Filename': name or '',
            'content': content_b64.decode('ascii'),
        }
        return mj_attachment, is_inline_image
422187
def create_email(filepaths, collection_name):
    
    outer = MIMEMultipart()
    outer.preamble = 'Here are some files for you'

    def add_file_to_outer(path):
        if not os.path.isfile(path):
            return

        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)

        if maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'text':
            # We do this to catch cases where text files have
            # an encoding we can't guess correctly.
            try:
                fp = open(path, 'r')
                msg = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            except UnicodeDecodeError:
                fp = open(path, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                encoders.encode_base64(msg)
                fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment',
                filename=os.path.basename(path))
        outer.attach(msg)

    outer.attach(MIMEText("Here are some files I've thrown at you."))
    
    for path in filepaths:
        add_file_to_outer(path)

    return outer
259648
def send_mail(subject, text_content, from_email, to, html_content=None, attachments=[], cc=[], bcc=[]):
    
    msg = EmailMultiAlternatives(subject, text_content, from_email, to, cc=cc, bcc=bcc)
    if html_content:
        msg.attach_alternative(html_content, "text/html")
    if attachments:
        for att in attachments:
            if att:

                mimetype = mimetypes.guess_type(att)[0]
                if str(mimetype) in ('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'):
                    try:
                        with open(att, 'r') as f:
                            email_embed_image(msg, att, f.read())
                    except Exception as e:
                        print(e)
                else:
                    msg.attach_file(att)
    return msg.send()
1150656
def send(self, attachment_failure=False):
		
		if not self.config['shutit.core.alerting.emailer.send_mail']:
			self.shutit.log('emailer.send: Not configured to send mail!',level=logging.INFO)
			return True
		msg = self.__compose()
		mailto = [self.config['shutit.core.alerting.emailer.mailto']]
		smtp = self.__get_smtp()
		if self.config['shutit.core.alerting.emailer.username'] != '':
			smtp.login(self.config['shutit.core.alerting.emailer.username'], self.config['shutit.core.alerting.emailer.password'])
		if self.config['shutit.core.alerting.emailer.mailto_maintainer']:
			mailto.append(self.config['shutit.core.alerting.emailer.maintainer'])
		try:
			self.shutit.log('Attempting to send email',level=logging.INFO)
			smtp.sendmail(self.config['shutit.core.alerting.emailer.mailfrom'], mailto, msg.as_string())
		except SMTPSenderRefused as refused:
			code = refused.args[0]
			if code == 552 and not attachment_failure:
				self.shutit.log("Mailserver rejected message due to " + "oversize attachments, attempting to resend without",level=logging.INFO)
				self.attaches = []
				self.lines.append("Oversized attachments not sent")
				self.send(attachment_failure=True)
			else:
				self.shutit.log("Unhandled SMTP error:" + str(refused),level=logging.INFO)
				if not self.config['shutit.core.alerting.emailer.safe_mode']:
					raise refused
		except Exception as error:
			self.shutit.log('Unhandled exception: ' + str(error),level=logging.INFO)
			if not self.config['shutit.core.alerting.emailer.safe_mode']:
				raise error
		finally:
			smtp.quit()
644571
def _create_related_attachment(self, filename, content, mimetype=None):
        
        attachment = super(EmailMultiRelated, self)._create_attachment(filename, content, mimetype)
        if filename:
            mimetype = attachment['Content-Type']
            del(attachment['Content-Type'])
            del(attachment['Content-Disposition'])
            attachment.add_header('Content-Disposition', 'inline', filename=filename)
            attachment.add_header('Content-Type', mimetype, name=filename)
            attachment.add_header('Content-ID', '<%s>' % filename)
        return attachment
580232
private static function mail()
    {
        $files = ['Mail', 'Mailable', 'SMTP'];
        $folder = static::$root.'Mailing'.'/';

        self::call($files, $folder);

        $files = ['SmtpParameterNotFoundException', 'MailViewNotFoundException'];
        $folder = $folder.'Exceptions/';

        self::call($files, $folder);
    }
954412
def build_attachment(self, text, target, attachment, thread):
        '''
        '''

        attachment = {
            'as_user': True,
            'text': text,
            'channel': target,
            'attachments': [
                {
                    'fallback': text,
                    'image_url': attachment
                }
            ]
        }
        if thread:
            attachment['thread_ts'] = thread
        return attachment
1240170
def email(to='medusa@sweeting.me', _from=default_from, subject='BOT MSG', message="Info email", attachments=None):
    """"""
    for attachment in attachments or []:
        filename = attachment.strip()
        try:
            result = run_cmd('uuencode %s %s | mailx -s "%s" %s' % (filename, filename, subject, to))[0]
            return "Sending email From: %s; To: %s; Subject: %s; Attachment: %s (%s)" % (_from, to, subject, filename, result or 'Succeded')
        except Exception as error:
            return str(error)

    if not attachments:
        p = os.popen("/usr/sbin/sendmail -t", "w")
        p.write("From: %s\n" % _from)
        p.write("To: %s\n" % to)
        p.write("Subject: %s\n" % subject)
        p.write("\n")   # blank line separating headers from body
        p.write('%s\n' % message)
        result = p.close()

    if not result:
        return "Sent email From: %s; To: %s; Subject: %s; Attachments: %s)" % (_from, to, subject, ','.join(attachments or []))
    else:
        return "Error: %s. Please fix Postfix:\n %s" % (result, help_str)
109179
function Attachment(options) {
    this.fileName = options.fileName;
    this.contents = options.contents;
    this.filePath = options.filePath;
    this.streamSource = options.streamSource;
    this.contentType = options.contentType;
    this.cid = options.cid;
}