I trying to make a php script to send one message to other person in moodle.
I've seen the message api and i make this
$message = new \core\message\message();
$message->component = 'moodle';
$message->name = 'instantmessage';
$message->userfrom = 318;
$message->userto = 323;
$message->subject = 'message subject 1';
$message->fullmessage = 'message body';
$message->fullmessageformat = FORMAT_MARKDOWN;
$message->fullmessagehtml = '<p>message body</p>';
$message->smallmessage = 'small message';
$message->notification = '0';
$message->contexturl = 'http://GalaxyFarFarAway.com';
$message->contexturlname = 'Context name';
$message->replyto = "random#example.com";
$content = array('*' => array('header' => ' test ', 'footer' => ' test ')); // Extra content for specific processor
$message->set_additional_content('email', $content);
$message->courseid = 107; // This is required in recent versions, use it from 3.2 on https://tracker.moodle.org/browse/MDL-47162
$messageid = message_send($message)
The problem is, when the user 323 send a reply message in the chat that is created in the moodle internal messaging, an error occurs (the message is surrounded by red) and never arrives.
And I really want it to be able to respond as if it were a normal conversation.
I don't know if I'm going wrong.
Thank you
I finally found it !!!
The problem is that first you have to create a conversation between the users and then send the message
if(!\core_message\api::get_conversation_between_users([$userfrom, $userto ])){
$conversation = \core_message\api::create_conversation(
\core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL,
[
$userfrom,
$userto
]
);
}
$message = new \core\message\message();
$message->component = 'moodle';
$message->name = 'instantmessage';
$message->userfrom = $userfrom ;
$message->userto = $userto;
$message->subject = 'Nuevo mensaje';
$message->fullmessage = $msg;
$message->fullmessageformat = FORMAT_MARKDOWN;
$message->fullmessagehtml = $msg;
$message->smallmessage = $msg;
$message->notification = '0';
$message->contexturl = '';
$message->contexturlname = 'Context name';
$message->replyto = "##########.###";
$content = array('*' => array('header' => '', 'footer' => ''));
$message->set_additional_content('email', $content);
$message->courseid = 107;
message_send($message);
It might be because the userto and userfrom need to be objects eg:
$userto = $DB->get_record('user', array('id' => 323));
$message->userfrom = $USER; // Current user.
$message->userto = $userto;
see https://docs.moodle.org/dev/Message_API#How_to_send_a_message
Related
I'll try to forward a mail with php-ews, but can't get it to work.
I have read the documentation for XML EWS
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-respond-to-email-messages-by-using-ews-in-exchange
but I'll guess I've missed something.
$request = new CreateItemType();
$request->MessageDisposition = MessageDispositionType::SEND_AND_SAVE_COPY;
$request->Items = new NonEmptyArrayOfAllItemsType();
$request->Items->ForwardedItem = new ForwardItemType();
$request->Items->ForwardedItem->ToRecipients = new MessageType();
$request->Items->ForwardedItem->ToRecipients->Mailbox = new EmailAddressType();
$request->Items->ForwardedItem->ToRecipients->Mailbox->MailboxName = 'Foo Bar';
$request->Items->ForwardedItem->ToRecipients->Mailbox->MailboxAddress = 'Foo#Bar.com';
$request->Items->ForwardedItem->ReferenceItemId = new ItemIdType();
$request->Items->ForwardedItem->ReferenceItemId->Id = 'AAMk.....AAA=';
$request->Items->ForwardedItem->ReferenceItemId->ChangeKey = 'CQAA.....GOP';
$request->Items->ForwardedItem->NewBodyContent = new BodyContentType();
$request->Items->ForwardedItem->NewBodyContent->Value = 'Test';
$request->Items->ForwardedItem->NewBodyContent->BodyType = BodyTypeType::HTML;
The error message I'll get is:
Fatal error: Uncaught SoapFault exception: [a:ErrorInvalidRequest] Id
must be non-empty.
This doesn't look right
$request->Items->ForwardedItem->ToRecipients = new MessageType();
$request->Items->ForwardedItem->ToRecipients->Mailbox = new EmailAddressType();
$request->Items->ForwardedItem->ToRecipients->Mailbox->MailboxName = 'Foo Bar';
$request->Items->ForwardedItem->ToRecipients->Mailbox->MailboxAddress = 'Foo#Bar.com';
ToRecipients should be an array of recipient types so i think it should be
$request->Items->ForwardedItem->ToRecipients = new ArrayOfRecipientsType();
$recipient = new EmailAddressType();
$recipient->Name = 'Homer Simpson';
$recipient->EmailAddress = 'hsimpson#example.com';
$request->Items->ForwardedItem->ToRecipients->Mailbox[] = $recipient;
I try to send attachment pdf file. I get the email but no attachmetn.
I have try to use https://github.com/sendinblue/APIv3-php-library/blob/master/docs/Model/SendSmtpEmail.mdenter
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['to'] = array(array('email'=>'email#email.com'));
$sendSmtpEmail['templateId'] = 39;
$sendSmtpEmail['params'] = array(
'NUMEROFACTURE'=> "12345",
'CODECLIENT' => "1234567",
'TOSEND' => "email1#email.net",
'MONTANTFACTURE'=> number_format(12, 2, ',', ' '),
);
$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['url']= __DIR__'/facture/Facture-'.$row["ClePiece"].'.pdf';
$attachement['name']= 'Facture-'.$row["ClePiece"].'.pdf';
$attachement['content']= "utf-8";
$sendSmtpEmail['attachment']= $attachement;
$sendSmtpEmail['headers'] = array('Content-Type'=>'application/pdf','Content-Disposition'=>'attachment','filename'=>'Facture-'.$row["ClePiece"].'.pdf',"charset"=>"utf-8");
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTransacEmail: ', $e->getMessage(), PHP_EOL;
}
According to the SendSmtpEmailAttachment documentation, you have two ways to attach a file using a url or a content.
url | Absolute url of the attachment (no local file).
content | Base64 encoded chunk data of the attachment generated on the fly
You are wrongly assigning "utf-8" to the content. This mean you need to convert the pdf data into a base64 chunk data. First, get the pdf path in your server as $pdfdocPath. Get the pdf content using file_get_contents method and encode it using base64_encode method. Finally, split the content in small chunks using chunk_split as shown in the next snippet:
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail();
$sendSmtpEmail['to'] = array(array('email'=>'email#email.com'));
$sendSmtpEmail['templateId'] = 39;
$sendSmtpEmail['params'] = array(
'NUMEROFACTURE'=> "12345",
'CODECLIENT' => "1234567",
'TOSEND' => "email1#email.net",
'MONTANTFACTURE'=> number_format(12, 2, ',', ' '),
);
$pdfdocPath = __DIR__.'/facture/Facture-'.$row["ClePiece"].'.pdf';
$b64Doc = chunk_split(base64_encode(file_get_contents($pdfdocPath)));
$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['name']= 'Facture-'.$row["ClePiece"].'.pdf';
$attachement['content']= $b64Doc;
$sendSmtpEmail['attachment']= $attachement;
$sendSmtpEmail['headers'] = array('Content-Type'=>'application/pdf','Content-Disposition'=>'attachment','filename'=>'Facture-'.$row["ClePiece"].'.pdf',"charset"=>"utf-8");
Update:
I checked the APIv3-php-library source code and I found that the constructor will do the validation of name and content.
$dataEmail = new \SendinBlue\Client\Model\SendEmail();
$dataEmail['emailTo'] = ['abc#example.com', 'asd#example.com'];
// PDF wrapper
$pdfDocPath = __DIR__.'/facture/Facture-'.$row["ClePiece"].'.pdf';
$content = chunk_split(base64_encode(file_get_contents($pdfDocPath)));
// Ends pdf wrapper
$attachment_item = array(
'name'=>'Facture-'.$row["ClePiece"].'.pdf',
'content'=>$content
);
$attachment_list = array($attachment_item);
// Ends pdf wrapper
$dataEmail['attachment'] = $attachment_list;
$templateId = 39;
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTemplate($templateId, $dataEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
$dataEmail= new \SendinBlue\Client\Model\SendEmail();
$dataEmail['emailTo'] = ['abc#example.com', 'asd#example.com'];
$dataEmail['attachmentUrl'] = "http://www.ac-grenoble.fr/ia07/spip/IMG/pdf/tutoriel_pdf_creator-2.pdf";
// if you want to use content attachment base64
// $b64Doc = chunk_split(base64_encode($data));
// $attachment_array = array(array(
// 'content'=>$b64Doc,
// 'name'=>'Facture-'.$row["ClePiece"].'.pdf'
// ));
// $dataEmail['attachment'] = $attachment_array;
//Don't forget to delete attachmentUrl
$templateId = 39;
$dataEmail = $dataEmail;
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');
$apiInstance = new SendinBlue\Client\Api\SMTPApi(new GuzzleHttp\Client(),$config);
try {
$result = $apiInstance->sendTemplate($templateId, $dataEmail);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling SMTPApi->sendTemplate: ', $e->getMessage(), PHP_EOL;
}
According to the documentaiton SMTPApi->sendTransacEmail function gets SendSmtpEmail object. That object has restrictions for the attachment attribute:
If templateId is passed and is in New Template Language format then only attachment url is accepted. If template is in Old template Language format, then attachment is ignored.
But SMTPApi->sendTemplate function don't have this restriction.
$credentials = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR-KEY');
$apiInstance = new SendinBlue\Client\Api\TransactionalEmailsApi(new GuzzleHttp\Client(),$credentials);
$sendSmtpEmail = new \SendinBlue\Client\Model\SendSmtpEmail([
'subject' => 'test email!',
'sender' => ['name' => 'from name', 'email' => 'from#mail.com'],
//'replyTo' => ['name' => 'test', 'email' => 'noreply#example.com'],
'to' => [[ 'name' => 'Tushar Aher', 'email' => 'receivedto#gmail.com']],
'htmlContent' => '<html><body><h1>This is a transactional email {{params.bodyMessage}}</h1></body></html>',
'params' => ['bodyMessage' => 'this is a test!']
]);
/*$attachement = new \SendinBlue\Client\Model\SendSmtpEmailAttachment();
$attachement['url']= FCPATH.'uploads/invoice/ticket-498410.pdf';
$attachement['name']= 'ticket-498410.pdf';
$attachement['content']= "utf-8";
$sendSmtpEmail['attachment']= $attachement;*/
// PDF wrapper
$pdfDocPath = FCPATH.'uploads/invoice/ticket-498410.pdf';
$content = chunk_split(base64_encode(file_get_contents($pdfDocPath)));
// Ends pdf wrapper
$attachment_item = array(
'name'=>'ticket-498410.pdf',
'content'=>$content
);
$attachment_list = array($attachment_item);
// Ends pdf wrapper
$sendSmtpEmail['attachment'] = $attachment_list;
try {
$result = $apiInstance->sendTransacEmail($sendSmtpEmail);
print_r($result);
} catch (Exception $e) {
echo $e->getMessage(),PHP_EOL;
}
I need to send mail to the admin with the inserted data using APi function ,
the function is look like that
public function requestbookingresort_post()
{
$languageid = $this->input->post('languageId');
$resort_id = $this->input->post('resortId');
$booking_from = $this->input->post('bookingFrom');
$booking_to = $this->input->post('bookingTo');
$contact_name = $this->input->post('contactName');
$contact_email = $this->input->post('contactEmail');
$contact_phone = $this->input->post('contactPhone');
$userid = $this->input->post('userId');
if (empty($languageid))
{
$languageRecord = getDefaultlanguage();
$languageid = $languageRecord->languageid;
}
$language_file = languagefilebyid($languageid);
$this->lang->load($language_file, $language_file);
if (empty($resort_id) || empty($booking_from) || empty($booking_to) || empty($contact_name) || empty($contact_email) || empty($contact_phone))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_in_booking');
$arr['data'] = array();
}
else
{
$dataArray = array(
"languageid" => $languageid,
"userid" => empty($userid) ? "0" : $userid,
"resortid" => $resort_id,
"bookingfrom" => date("Y-m-d", strtotime($booking_from)),
"bookingto" => date("Y-m-d", strtotime($booking_to)),
"contactname" => $contact_name,
"contactemail" => $contact_email,
"contactphone" => $contact_phone,
"requestdatetime" => date("Y-m-d H:i:s"),
);
$this->load->model("Resort_model");
$booking_id = $this->Resort_model->saveBookingRequest($dataArray);
if (empty($booking_id))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_occurred');
$arr['data'] = array();
}
else
{
$arr['status'] = 'success';
$arr['statusMessage'] = lang('booking_request_submit');
$arr['data'] = array();
}
}
$response = array(
"response" => $arr
);
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
But i'm new at codeigniter and didn't know how to get this passed data from the database to send mail with that to the admin mail or something ?
Try this.
public function requestbookingresort_post()
{
// Your operations
$response = array(
"response" => $arr
);
$this->sendMail($response)
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
public function sendMail($response)
{
$settings=$this->Some_model->getEmailSettings();
$mail = new PHPMailer();
$mail->IsSMTP(); // we are going to use SMTP
$mail->SMTPAuth = true; // enabled SMTP authentication
$mail->SMTPSecure = "ssl"; // prefix for secure protocol to connect to the server
$mail->Host = $settings->host; // setting GMail as our SMTP server
$mail->Port = $settings->port; // SMTP port to connect to GMail
$mail->Username = $settings->email; // user email address
$mail->Password = $settings->password; // password in GMail
$mail->SetFrom($settings->sent_email, $settings->sent_title); //Who is sending the email
$mail->AddReplyTo($settings->reply_email,$settings->reply_email); //email address that receives the response
$mail->Subject = "Your Booking has been confirmed";
$mail->IsHTML(true);
$body = $this->load->view('path/email_template', $response, true);
$mail->MsgHTML($body);
$destination = $response['contactEmail']; // Who is addressed the email to
$mail->AddAddress($destination);
if(!$mail->Send()) {
$data['code']=300;
$data["message"] = "Error: " . $mail->ErrorInfo;
}
}
Make sure you have PHPMailer in your libraries and you are loading the library in your constructor and I hope you are keeping Email settings in your database. If not you can manually provide host, port, username and password fields
I would like to send emails only to users that have completed a specific course and add a pdf file (a certificate for completing the course) as attachment to the email, and do so at a specific time using moodle cron.
I have looked at some plugins to find out how it's done, but I'm still not sure how exactly I should do this.
I need:
1. to know how I would add an attachment to an email (and which API to use),
2. how I would use cron to send the emails to the desired group at a certain time,
3. how to retrieve users that have completed the course so that I could send emails (with attachment) to them.
Thanks in advance.
(I'm using moodle version 3.0)
This is an overview.
First create a local plugin. For example /local/yourplugin
https://docs.moodle.org/dev/Local_plugins
Then set up a message provider
https://docs.moodle.org/dev/Message_API
defined('MOODLE_INTERNAL') || die();
in local/yourplugin/db/messages.php
$messageproviders = array (
'coursecompleted' => array (
),
Then add an event observer - you will want to respond to the course_completed event
https://docs.moodle.org/dev/Event_2
in /local/yourpluginname/db/events.php
have something like
$observers = array(
array(
'eventname' => '\core\event\course_completed',
'callback' => 'local_yourplugin_observer::course_completed',
),
);
Now add the message code
Add something like this to '/local/message/classes/observer.php'
defined('MOODLE_INTERNAL') || die();
class local_yourplugin_observer {
/**
* Triggered when 'course_completed' event is triggered.
*
* #param \core\event\course_completed $event
* #return bool
*/
public static function course_completed(\core\event\course_completed $event) {
// Your code here.
$message = new \core\message\message();
$message->component = 'local_yourplugin'; // Name of your local plugin.
$message->name = 'coursecompleted'; // Name of message provider.
$message->userfrom = $USER;
$message->userto = $user;
$message->subject = 'message subject 1';
$message->fullmessage = 'message body';
$message->fullmessageformat = FORMAT_MARKDOWN;
$message->fullmessagehtml = '<p>message body</p>';
$message->smallmessage = 'small message';
$message->notification = '0';
$message->contexturl = 'http://GalaxyFarFarAway.com';
$message->contexturlname = 'Context name';
$message->replyto = "random#example.com";
$content = array('*' => array('header' => ' test ', 'footer' => ' test ')); // Extra content for specific processor
$message->set_additional_content('email', $content);
// Create a file instance.
$usercontext = context_user::instance($user->id);
$file = new stdClass;
$file->contextid = $usercontext->id;
$file->component = 'user';
$file->filearea = 'private';
$file->itemid = 0;
$file->filepath = '/';
$file->filename = '1.txt';
$file->source = 'test';
$fs = get_file_storage();
$file = $fs->create_file_from_string($file, 'file1 content');
$message->attachment = $file;
$messageid = message_send($message);
}
}
How to send email with text/plain, text/html and attaches in zf2 ?
I use this code to send email with smtp:
$files = $this->params()->fromFiles();
$smtp = new \Zend\Mail\Transport\Smtp();
$smtp->setAutoDisconnect(true);
$optn = new \Zend\Mail\Transport\SmtpOptions(array(
'host' => 'mail.myserver.com',
'connection_class' => 'login',
'connection_config' => array(
'username' => 'user#myserver.com',
'password' => 'mypassword',
),
));
$smtp->setOptions($optn);
$htmlPart = new \Zend\Mime\Part('<p>some html</p>');
$htmlPart->type = Mime::TYPE_HTML;
$textPart = new \Zend\Mime\Part('some text');
$textPart->type = Mime::TYPE_TEXT;
$i=0;
$attaches = array();
foreach($files as $file){
if ($file['error'])
continue;
$attaches[$i] = new \Zend\Mime\Part(file_get_contents($file['tmp_name']));
$attaches[$i]->type = $file['type'].'; name="'.$file['name'].'"';
$attaches[$i]->encoding = 'base64';
$attaches[$i]->disposition = 'attachment';
$attaches[$i]->filename = $file['name'];
$i++;
}
$parts = array();
if (count($attaches)>0) {
$parts = array_merge(array($textPart,$htmlPart),$attaches);
$type = Mime::MULTIPART_MIXED;
}
else{
$parts = array($textPart, $htmlPart);
$type = Mime::MULTIPART_ALTERNATIVE ;
}
$body = new \Zend\Mime\Message();
$body->setParts($parts);
$message = new \Zend\Mail\Message();
$message->setFrom('user#myserver.com');
$message->addTo('receiver#myserver.com');
$message->setSubject('subject');
$message->setEncoding("UTF-8");
$message->setBody($body);
$message->getHeaders()->get('content-type')->setType($type);
$smtp->send($message);
If I attach files, it sends files and contents but it shows plain and html text together in receiver inbox:
<p>some html</p>
some text
When I don't attach any files, it shows html text singly:
some html
Any help?
Currently there is no easy way in ZF2 (2.2) to combine a multipart/alternative body (html with text alternative for clients that cannot/do-not-want-to use html) with attachments.
If you add the 'multipart/alternative' content-type header to the entire message, in some email clients the attachment (link) will not be displayed.
The solution is to split the message in two, the body (text and html) and the attachment:
http://jw-dev.blogspot.com.es/2013/01/zf2-zend-mail-multipartalternative-and.html
an example:
$content = new MimeMessage();
$htmlPart = new MimePart("<html><body><p>Sorry,</p><p>I'm going to be late today!</p></body></html>");
$htmlPart->type = 'text/html';
$textPart = new MimePart("Sorry, I'm going to be late today!");
$textPart->type = 'text/plain';
$content->setParts(array($textPart, $htmlPart));
$contentPart = new MimePart($content->generateMessage());
$contentPart->type = 'multipart/alternative;' . PHP_EOL . ' boundary="' . $content->getMime()->boundary() . '"';
$attachment = new MimePart(fopen('/path/to/test.pdf', 'r'));
$attachment->type = 'application/pdf';
$attachment->encoding = Mime::ENCODING_BASE64;
$attachment->disposition = Mime::DISPOSITION_ATTACHMENT;
$body = new MimeMessage();
$body->setParts(array($contentPart, $attachment));
$message = new Message();
$message->setEncoding('utf-8')
->addTo('mywife#home.com')
->addFrom('myself#office.com')
->setSubject('will be late')
->setBody($body);
$transport = new SmtpTransport();
$options = new SmtpOptions($transportConfig),
));
$transport->setOptions($options);
$transport->send($message);
For the above you would need the following use statements:
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
use Zend\Mime\Mime;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
ZF1 had a _buildBody() method in Zend_Mail_Transport_Abstract which did this automatically.
I have found it a better solution so I am writing it.
Namespace YourNamesapace;
use Zend\Mail\Message as ZendMessage;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Message as MimeMessage;
use Zend\Mail\Transport\Sendmail;
class Testmail
{
public static function sendMailWithAttachment($to, $subject, $htmlMsg, $dir, $fileName)
{
$fileFullPath = $dir . '/' . $fileName;
// Render content from template
$htmlContent = $htmlMsg;
// Create HTML part
$htmlPart = new MimePart($htmlContent);
$htmlPart->type = "text/html";
// Create plain text part
$stripTagsFilter = new \Zend\Filter\StripTags();
$textContent = str_ireplace(array("<br />", "<br>"), "\r\n", $htmlContent);
$textContent = $stripTagsFilter->filter($textContent);
$textPart = new MimePart($textContent);
$textPart->type = "text/plain";
// Create separate alternative parts object
$alternatives = new MimeMessage();
$alternatives->setParts(array($textPart, $htmlPart));
$alternativesPart = new MimePart($alternatives->generateMessage());
$alternativesPart->type = "multipart/alternative;\n boundary=\"".$alternatives->getMime()->boundary()."\"";
$body = new MimeMessage();
$body->addPart($alternativesPart);
$attachment = new MimePart( file_get_contents($fileFullPath) );
$attachment->type = \Zend\Mime\Mime::TYPE_OCTETSTREAM;
$attachment->filename = basename($fileName);
$attachment->disposition = \Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
$attachment->encoding = \Zend\Mime\Mime::ENCODING_BASE64;
$body->addPart($attachment);
// Create mail message
$mailMessage = new ZendMessage();
$mailMessage->setFrom('noreply#example.com', 'from Name');
$mailMessage->setTo($to);
$mailMessage->setSubject($subject);
$mailMessage->setBody($body);
$mailMessage->setEncoding("UTF-8");
$mailMessage->getHeaders()->get('content-type')->setType('multipart/mixed');
$transport = new Sendmail();
$transport->send($mailMessage);
}
}
Set the type from :
$attaches[$i]->type = $file['type'].'; name="'.$file['name'].'"';
To:
$attaches[$i]->type = \Zend\Mime\Mime::TYPE_OCTETSTREAM;
You will also want to confirm that if you are using an SMTP service that they allow attachements through the protocol.
E-Mail Messages with Attachments
$mail = new Zend\Mail\Message();
// build message...
$mail->createAttachment($someBinaryString);
$mail->createAttachment($myImage,
'image/gif',
Zend\Mime\Mime::DISPOSITION_INLINE,
Zend\Mime\Mime::ENCODING_BASE64);
If you want more control over the MIME part generated for this attachment you can use the return value of createAttachment() to modify its attributes. The createAttachment() method returns a Zend\Mime\Part object:
$mail = new Zend\Mail\Message();
$at = $mail->createAttachment($myImage);
$at->type = 'image/gif';
$at->disposition = Zend\Mime\Mime::DISPOSITION_INLINE;
$at->encoding = Zend\Mime\Mime::ENCODING_BASE64;
$at->filename = 'test.gif';
$mail->send();
An alternative is to create an instance of Zend\Mime\Part and add it with addAttachment():
$mail = new Zend\Mail\Message();
$at = new Zend\Mime\Part($myImage);
$at->type = 'image/gif';
$at->disposition = Zend\Mime\Mime::DISPOSITION_INLINE;
$at->encoding = Zend\Mime\Mime::ENCODING_BASE64;
$at->filename = 'test.gif';
$mail->addAttachment($at);
$mail->send();
Reference1
Reference2
Reference3