Hello there!
We created a custom code in /custom/Extension/modules/Schedulers/Ext/ScheduledTasks
that makes possible the import of emails and documents into the CRM. The new emails are saved in “opportunity” module using the email subject as title and the body as description, while the attachments are imported in “documents”. The final goal would be to bond everything, in order to keep the process smooth and be able to access all the files directly through the account, opportunity or document subpanels. At the moment, we didn’t have any issue importing the mail and attachment; however, we are missing the associatiation between the opportunity and document below the account subpanel_list
I’ll share the code below, hope it helps:
Version 7.13.1
Sugar Version 6.5.25 (Version 344)
<?php
//WARNING: The contents of this file are auto-generated
$job_strings[] = 'CreaOppDaMail';
// Include SuiteCRM configuration files
require_once('include/entryPoint.php');
// Set current user to perform the action
global $current_user;
$current_user = new User();
$current_user->retrieve('test@domain.it'); // Replace USER_ID with the appropriate user
// Read email IMAP and create new record Opportunity
function CreaOppDaMail() {
//Configure the information of IMAP account
$mailbox = '{pop:993/ssl}INBOX';
$username = 'test@domain.it';
$password = 'xxxxxxxx';
// IMAP connection
$inbox = imap_open($mailbox, $username, $password) or die('Connessione IMAP fallita: ' . imap_last_error());
// Get all emails in inbox
$emails = imap_search($inbox, 'ALL');
if ($emails) {
foreach ($emails as $email_number) {
$header = imap_headerinfo($inbox, $email_number);
$subject = $header->subject;
//$message = imap_fetchbody($inbox, $email_number, 1);
$UpSubject = strtoupper($subject);
if (strpos($UpSubject,"RDO")!== false || (strpos($UpSubject,"OFFERTA")!== false && strpos($UpSubjectt,"STANDARD")!== false)) {
$message=imap_fetchbody($inbox, $email_number, 1.2);
$message=quoted_printable_decode(str_replace("=\r\n","",$message));
$message=strip_tags($message);
$message=str_replace("'","\'",$message);
// Retrieve email data and create new opportunity record Opportunity
$OpportunityBean = BeanFactory::newBean('Opportunities');
$OpportunityBean->name = $subject; // Email subject as opportunity title
$OpportunityBean->description = $message; // Email body as opportunity description
$OpportunityBean->amount = 'Opportunity amount';
$OpportunityBean->assigned_user_id = $current_user->id;
// Save the opportunity
if ($OpportunityBean->save()) {
// Set the email as read and remove it
//imap_setflag_full($inbox, $email_number, "\\Seen");
imap_delete($inbox, $email_number);
}
// Retrieve attachments from the email
$attachments = imap_fetchstructure($inbox, $email_number);
if ($attachments->parts) {
foreach ($attachments->parts as $part_number => $part) {
$attachment_name = $part->dparameters[0]->value;
$attachment_data = imap_fetchbody($inbox, $email_number, $part_number + 1);
if(strpos($attachment_name,".pdf")>0){
$OpportunityBean->load_relationship('documents');
$documentBean = BeanFactory::newBean('Documents');
// Create new document in suite CRM and link it to the Opportunity
$documentBean->document_name = $attachment_name;
$documentBean->revision = 1;
$documentBean->category_id = 'Marketing'; // Replace with the ID of the correct category
$documentBean->filename = 'upload/' . $attachmentName;
$documentBean->file_mime_type = $part->type;
$documentBean->file = base64_encode($attachment_data);
$documentBean->assigned_user_id = $current_user->id;
// Save the document
if ($documentBean->save()) {
//Generate the next revision for the document
$documentId = $documentBean->id; // replace with the document ID
$revisionNumber = generateNextRevisionNumber($documentId);
// Create a Revision subject
$revision = new DocumentRevision();
$revision->document_id = $documentId;
$revision->revision = $revisionNumber;
$revision->description = 'Revisione automatica da Email';
$revision->date_entered = gmdate('Y-m-d H:i:s');
$revision->assigned_user_id = $current_user->id;
$revision->file_mime_type = 'application/pdf';
$revision->filename = $attachment_name;
// save the new revision in the database database
if ($revision->save()) {
/*
// Associate the attachment to the revision
$revision->load_relationship('documents_documentsrevision');
$revision->documents_documentsrevision->add($documentId);
// save the attachment as part of the revision (Modify using the appropriate MIME path)
$attachmentPath = 'upload/'.$attachment_name;
$revision->file_mime_type = 'application/pdf';
$revision->setDocumentRevisionFile($attachmentPath, 'application/pdf');
$revision->save();
// Link the opportunity to revision
$opportunity->load_relationship('opportunity_revisions_1');
$opportunity->opportunity_revisions_1->add($revision->id);
$opportunity->save();
*/
// save the attachment on the file system
$attachmentPath = 'upload/' . $revision->id;
file_put_contents($attachmentPath, base64_decode($attachment_data));
}
/*
// save the attachment
$documentBean->filename = 'uploads/' . $documentBean->id . '_' . $documentBean->document_revision_id . '.tmp';
$documentBean->document_revision_id = create_guid();
$documentBean->doc_type = 'Marketing';
$documentBean->revision = 1;
$documentBean->document_revision_id = $documentBean->revision;
$documentBean->file = $attachment_data;
$documentBean->file_mime_type = $part->type;
$documentBean->save();
*/
$OpportunityBean->documents->add($documentBean);
}
}
}
}
}
}
imap_expunge($inbox); //permanently delete email
}
// Close IMAP connection
imap_close($inbox);
}
function generateNextRevisionNumber($documentId) {
$query = "SELECT MAX(revision) AS max_revision FROM documents_revisions WHERE document_id = '{$documentId}'";
$result = $GLOBALS['db']->query($query);
$row = $GLOBALS['db']->fetchByAssoc($result);
if ($row && isset($row['max_revision'])) {
// If any existing revision, increase the number by 1
$maxRevision = (int) $row['max_revision'];
return $maxRevision + 1;
} else {
// If no existing revisions, start again from 1
return 1;
}
}
?>