Creating messages (ie drafts) in Gmail with IMAP/SMTP? - php

I've done quite a bit of inbox manipulation with Gmail via IMAP functions in PHP, but one thing I haven't found is a way to create messages. I'm not sure if IMAP or SMTP is required, but I would like to use PHP to create a new message (specifically a draft) that is stored in my inbox with everything ready to hit send at a later date. How do I go about this?

You might want to look at imap_mail_compose()
Edit
This doesn't create the message on the server. You need to use imap_append() also.
Further Edit
This seems to work ok:
<?php
$rootMailBox = "{imap.gmail.com:993/imap/ssl}";
$draftsMailBox = $rootMailBox . '[Google Mail]/Drafts';
$conn = imap_open ($rootMailBox, "sdfsfd#gmail.com", "password") or die("can't connect: " . imap_last_error());
$envelope["to"] = "test#test.com";
$envelope["subject"] = "Test Draft";
$part["type"] = TYPETEXT;
$part["subtype"] = "plain";
$part["description"] = "part description";
$part["contents.data"] = "Testing Content";
$body[1] = $part;
$msg = imap_mail_compose($envelope, $body);
if (imap_append($conn, $draftsMailBox, $msg) === false) {
die( "could not append message: " . imap_last_error() ) ;
}

Related

How to exclude IMAP-Folder in INBOX from reading with imap_open (PHP)

I´m working on a script in PHP that reads all mails in INBOX, detects special mails via Header-Info and moves processed mails into a folder. I want to exclude this folder from further reading, at the moment my script also finds mails that are already in the processed folder. I´m using the imap_open function like this:
$host = "{" . HOST . ":" . PORT . "/imap/ssl/novalidate-cert}INBOX";
$email = EMAIL;
$password = PASSWORD;
$imap = imap_open($host, $email, $password) or die("Cannot Connect " . imap_last_error());
$emailIds = imap_search($imap, 'FROM ' . SCAN_EMAIL_FOR_OFFERS, SE_UID);
if (!empty($emailIds)) {
foreach ($emailIds as $emailId) {
$email = new readMail();
$header = $email->get_headerinfo($imap, $emailId);
if (strpos($header->subject, "Angebot Nr.") != false) {
...Doing stuff...
$email->move_mail($imap, $emailId, MOVE_PROCESSED_TO_FOLDER);
}
}
} else {
echo "No new offers.";
}
imap_close($imap);
Regards
Edit: This is the move-func of readMail-Class...
function move_mail($imap, $uid, $inboxFolder) {
$msgNo = imap_msgno($imap, $uid);
$movingMail = imap_mail_move($imap, $msgNo, 'INBOX/'. $inboxFolder);
if($movingMail == false) {die(imap_last_error());}
}

Is any other way to read message from webmail on cpanel using PHP with out using IMAP function

I'm integrating PHP webmail read functionality in php. I already tried using IMAP functions. But it could not connect.So I just ask you is there any possibility to get messages from webamil with out using IMAP function.
Below is my IMAP Code. Can you check the code also give me suggestions for why doesn't work. I'm looking forward for your valuable reply.
$emailAddress = 'info#example.com'; // Full email address
$emailPassword = 'xxxxxxxx'; // Email password
$domainURL = 'example.com'; // Your websites domain
$useHTTPS = false;
/* BEGIN MESSAGE COUNT CODE */
$inbox = imap_open('{'.$domainURL.':143/notls}INBOX',$emailAddress,$emailPassword) or die('Cannot connect to domain:' . imap_last_error());
$oResult = imap_search($inbox, 'UNSEEN');
if(empty($oResult))
$nMsgCount = 0;
else
$nMsgCount = count($oResult);
imap_close($inbox);
echo('<p>You have '.$nMsgCount.' unread messages.</p>');
Thanks in advance

Wordpress PHP Server Script to send email

I am trying to get a server script to use wp_mail() and send an email to a user. I am doing this as part of a password reset routine, and calling the script with Ajax from the user's side.
I am getting the following error from my server script:
Fatal error: Call to undefined function wp_mail() in /var/www/abc-php/pwd.php on line 57
I cannot seem to find an answer to my question, so maybe I am asking incorrectly. Is what I am doing possible?
My server script (pwd.php) contains:
<?php
$setFromId = "info#abc.com.au";
$setFromName = "Info # abc";
$replyToId = "info#abc.com.au";
$replyToName = "Info # abc";
$sendToEmail = base64_decode($_GET["ste"]); //the URL in AJAX call contains base64 encoded data
$resetPwd = base64_decode($_GET["rp"]);
$resetSalt = base64_decode($_GET["rs"]);
$param = $_GET["var"];
$username = "xxxxxxxxx";
$password = "xxxxxxxx";
$host = "localhost";
$database = "xxxxxxxxx";
$con = mysqli_connect($host, $username, $password, $database);
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
switch ($param) {
case "PWDRES": // Query 1: Current Logged In Partner Details
$mysqli = new mysqli($host, $username, $password, $database);
if (mysqli_connect_errno()) {
echo '<p>Unable to connect to the server at this time to update and send password. Please contact SMA for help or try again.</p>';
} else {
$myquery = "UPDATE abc_users
SET `password` = SHA2('" . $resetPwd . $resetSalt . "', 512),
`salt_value` = SHA2('" . $resetSalt . "', 512)
WHERE email_user_id = '" . $sendToEmail . "'";
mysqli_query($mysqli, $myquery);
if($mysqli->affected_rows >= 1) {
$headers = 'Reply-To: <' . $replyToName . '> ' . $replyToId;
$subject = "Password Reset - Confidential";
$body = "Subject: " . $subject . "<br/><br/>Your new password is: <br/><strong>" . $resetPwd . "</strong><br/><br/>Please ensure you reset this password next time you log in.";
$mail = wp_mail($sendToEmail, $subject, $body, $headers);
echo "Password was successfully reset and sent to " . $sendToEmail;
} else if($mysqli->affected_rows == 0) {
echo "No user id row was updated in the process of resetting password. Please try again.";
} else if($mysqli->affected_rows < 0) {
echo "There was an SQL error updating the user id password table. Please contact SMA for help.";
};
};
break;
case "OTHER1"
etc, etc, etc...
default;
};
};
unset($con);
unset($myquery);
unset($mysqli);
?>
Any help is appreciated.
You need to include wp-load.php in your file....
Just put this in top of your file.
require_once( dirname(__FILE__) . '/wp-load.php' );
The problem is you are not including Wordpress, so you are not using it at all (and it isn't including its libraries).
Plus, this is unrelated to the question, but you have a weakness in your code :
Any users can define the recipient of the email.

Sending emails to multiple recipients (PHP, My SQL)

Hi I am new to this and only have a basic understanding on PHP so any help would be most welcome. Basically I am trying to send an email via PHP that can have multiple recipients. The content also needs to display a list of users following certain criteria. I have got the script to look at the database and send an email however it only sends it to one person and only lists one person in the content. Please could someone advise on how to change that to email / display to multiple recipients. I know that there should be at least three people it is sent to.
Any help / pointers would be most welcome. Thank you.
<?php
session_start();
require_once('../config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(database_name);
if(!$db) {
die("Unable to select database");
}
$result = mysql_query("SELECT username FROM users WHERE user_type='admin'");
while($result_email = mysql_fetch_array($result))
$to = $result_email['username'];
$result2 = mysql_query("SELECT * FROM users
WHERE ticked='1' AND NOT user_type='super'");
while($result2 = mysql_fetch_array($result2))
$body = $result2['fname'] . " " . $result2['lname'] . " , " . $result2['username'];
mail ($to, 'Subject', $body);
?>
You can do that. They just need to be comma separated.
$to = "email#email.com, email2#email2.com";
Reference: http://php.net/manual/en/function.mail.php
Also, your code is a little confusing the way you have pasted it. But if you are loading all the emails in a while loop. Then you want to send it after the while. For example:
You want it to be:
//create an empty $to string
$to = '';
//add all the emails
while($emails as $email)
{
$to .= $email . ',';
}
//remove the last comma
rtrim($to, ",");
//send away
mail($to, $subject, $message);
your code is wrong. you would have error if you used it. you need to use implode to add comma between the emails. check your php. i corrected but you have to use while statement right. you have multiple mysql query for one job. also you should not use mysql_query. use PDO instead...
you should use it like this
<?php
while($row = mysql_fetch_array($result2))
{
$addresses[] = $row['username'];
}
$to = implode(", ", $addresses);
?>
with your code
<?php
session_start();
require_once('../config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(database_name);
if(!$db) {
die("Unable to select database");
}
$result = mysql_query("SELECT username FROM users WHERE user_type='admin'");
while($row = mysql_fetch_array($result2))
{
$addresses[] = $row['username'];
}
$to = implode(", ", $addresses);
$result2 = mysql_query("SELECT * FROM users
WHERE ticked='1' AND NOT user_type='super'");
$body = mysql_fetch_array($result2);
$body = $result2['fname'] . " " . $result2['lname'] . " , " . $result2['username'];
mail ($to, 'Subject', $body);
?>
You are overwriting the value of $to repeatedly with the statement $to = $result_email['username'];. You should make a comma-separated list instead. But for goodness' sake,
Consider setting the addresses as BCC, and set TO to something that does not matter, e.g. noreply#[yourdomain] to hide the recipients' addresses from each other.
Use DB-access that is not deprecated: PDO
Your call to mail() is not in a loop, so it will only send one e-mail.
And your while loop where you're setting $to is simply overwriting the previous value each time the loop iterates.
So in the end $to will be set to the last username the first query returns. And your $body will be the body you want for the last row your second query returns.

Getting the name of an Exchange mailbox to connect to it programmatically

I am writing a PHP script to connect to an Exchange server and read messages from a mailbox. I have it connecting to my inbox just fine. What I'm trying to do now is get PHP to connect to a different mailbox that I have access to (Let's call it "Test Mailbox").
I tried this code:
imap_open( '{mail.domain.com:143}Test Mailbox', 'myusername', 'mypassword' );
But it said the mailbox doesn't exist. How can I get a list of mailboxes or get the path to the mailbox?
You should really think about doing this with Exchange Web Services (EWS). This will get you the data you want via SOAP versus IMAP which isn't going to be able to produce alot of things.
You can get a list of mailboxes with imap_getmailboxes(). As for selecting a mailbox, try without the leading /.
From php.net:
$mbox = imap_open("{mail.domain.com:143}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$list = imap_getmailboxes($mbox, "{mail.domain.com:143}", "*");
if (is_array($list)) {
foreach ($list as $key => $val) {
echo "($key) ";
echo imap_utf7_decode($val->name) . ",";
echo "'" . $val->delimiter . "',";
echo $val->attributes . "<br />\n";
}
} else {
echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
}
imap_close($mbox);

Categories