0

I am creating a Plugin that displays e-mails as posts. I used the following PHP to access those emails:

<?php
class Email_reader {
    // imap server connection
    public $conn;
    // inbox storage and inbox message count
    private $inbox;
    private $msg_cnt;
    // email login credentials
    private $server = 'website.com';
    private $user   = '[email protected]';
    private $pass   = 'PASSWORD';
    private $port   = 993; // adjust according to server settings
    // connect to the server and get the inbox emails
    function __construct() {
        $this->connect();
        $this->inbox();
    }
    // close the server connection
    function close() {
        $this->inbox = array();
        $this->msg_cnt = 0;
        imap_close($this->conn);
    }
    // open the server connection
    // the imap_open function parameters will need to be changed for the particular server
    // these are laid out to connect to a Dreamhost IMAP server
    function connect() {
        $this->conn = imap_open('{'.$this->server.'/notls}', $this->user, $this->pass);
    }
    // move the message to a new folder
    function move($msg_index, $folder='INBOX.Processed') {
        // move on server
        imap_mail_move($this->conn, $msg_index, $folder);
        imap_expunge($this->conn);
        // re-read the inbox
        $this->inbox();
    }
    // get a specific message (1 = first email, 2 = second email, etc.)
    function get($msg_index=NULL) {
        if (count($this->inbox) <= 0) {
            return array();
        }
        elseif ( ! is_null($msg_index) && isset($this->inbox[$msg_index])) {
            return $this->inbox[$msg_index];
        }
        return $this->inbox[0];
    }
    // read the inbox
    function inbox() {
        $this->msg_cnt = imap_num_msg($this->conn);
        $in = array();
        for($i = 1; $i <= $this->msg_cnt; $i++) {
            $in[] = array(
                'index'     => $i,
                'header'    => imap_headerinfo($this->conn, $i),
                'body'      => imap_body($this->conn, $i),
                'structure' => imap_fetchstructure($this->conn, $i)
            );
        }
        $this->inbox = $in;
    }
}
$emails = new Email_reader;
echo "<pre>";
    var_dump($emails);

Now I created a custom post type and I want to assign those emails to the custom post type how can I achieve it. The code I used is

//// Register Post Type.
if(!function_exists('my_email_custom_post_type')){
    function my_email_custom_post_type() {
        $labels = array(
            'name'                => __( 'E-mail Inbox','domain'),
            'singular_name'       => __( ' E-mail','domain'),
            'menu_name'           => __( 'E-mail Inbox','domain'),
            'parent_item_colon'   => __( 'Parent tickets','domain'),
            'all_items'           => __( 'All E-mail tickets','domain'),
            'view_item'           => __( 'View E-mail tickets','domain'),
            'search_items'        => __( 'Search E-mail tickets','domain'),
            'not_found'           => __( 'Not Found','domain'),
            'supports'          =>__( 'title', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'revisions', 'page-attributes' ),
            'not_found_in_trash'  => __( 'Not found in Trash','domain')
        );


        $args = array(
            'label'               => __( 'E-mail Inbox','domain'),
            'description'         => __( 'E-mail','domain'),
            'labels'              => $labels,
            'supports'            => array( 'title'),
            'capabilities' => array(
             'create_posts' => false, // Removes support for the "Add New" function ( use 'do_not_allow' instead of false for multisite set ups )
  ),
            'public'              => true,
            'hierarchical'        => false,
            'show_ui'             => true,
            'menu_icon'           => 'dashicons-feedback',
            'show_in_menu'        => true,
            'show_in_nav_menus'   => true,
            'show_in_admin_bar'   => true,
            'has_archive'         => true,
            'can_export'          => true,
            'exclude_from_search' => false,
            'yarpp_support'       => true,
            'publicly_queryable'  => true,
            'capability_type'     => 'page'
        );
        register_post_type( 'post-email', $args );
    }
    add_action( 'init', 'my_email_custom_post_type', 0 );
}


require_once plugin_dir_path( __FILE__ ) . 'emailpipe.php';


$args = array(
'post_type' => 'my-email',
);

$emails = new WP_query($args);

while($emails->have_posts()) {
$emails->the_post();

?>
<h3><?php the_title(); ?></h3>
<?php the_excerpt();?>
<?php
}

This is for sure not working can you please advise me.

2
  • can you take the code from your gist and embed it in your question? And can you describe what you mean by assign email to a post? Are you trying to import emails into your site as posts?
    – Tom J Nowell
    Dec 3, 2021 at 20:17
  • @TomJNowell I have embedded the code from my gist. As you can see, $emails stores the emails, and imap_headerinfo() stores the header and so on. Now I want those to convert intro the_title(), the_content() in WordPress so I can use them as a post type. How can I achieve that? I hope you get my question now. |
    – Rohit kc
    Dec 6, 2021 at 5:16

1 Answer 1

0

It's very easy use can use wordpress default function wp_insert_post() to create post programtically. See this for more detail.

Given below is the code that I modified:

<?php
class Email_reader {
    // imap server connection
    public $conn;
    // inbox storage and inbox message count
    private $inbox;
    private $msg_cnt;
    // email login credentials
    private $server = 'website.com';
    private $user   = '[email protected]';
    private $pass   = 'PSSWORD';
    private $port   = 993; // adjust according to server settings
    // connect to the server and get the inbox emails
    function __construct() {
        $this->connect();
        $this->inbox();
    }
    // close the server connection
    function close() {
        $this->inbox = array();
        $this->msg_cnt = 0;
        imap_close($this->conn);
    }
    // open the server connection
    // the imap_open function parameters will need to be changed for the particular server
    // these are laid out to connect to a Dreamhost IMAP server
    function connect() {
        $this->conn = imap_open('{'.$this->server.'/notls}', $this->user, $this->pass);
    }
    // move the message to a new folder
    function move($msg_index, $folder='INBOX.Processed') {
        // move on server
        imap_mail_move($this->conn, $msg_index, $folder);
        imap_expunge($this->conn);
        // re-read the inbox
        $this->inbox();
    }
    // get a specific message (1 = first email, 2 = second email, etc.)
    function get($msg_index=NULL) {
        if (count($this->inbox) <= 0) {
            return array();
        }
        elseif ( ! is_null($msg_index) && isset($this->inbox[$msg_index])) {
            return $this->inbox[$msg_index];
        }
        return $this->inbox[0];
    }
    // read the inbox
    function inbox() {
        $this->msg_cnt = imap_num_msg($this->conn);
        $in = array();
        for($i = 1; $i <= $this->msg_cnt; $i++) {
            $in[] = array(
                'index'     => $i,
                'header'    => imap_headerinfo($this->conn, $i),
                'body'      => imap_body($this->conn, $i),
                'structure' => imap_fetchstructure($this->conn, $i)
            );
        }
        $this->inbox = $in;
    }
    function total_msg(){
        return imap_num_msg($this->conn);;
    }
}

$emails = new Email_reader;    
$total =  $emails->total_msg();

    for ($j=1; $j <= $total; $j++) { 
       $mail =  $emails->get($j);

       $post_array = array(        
        'post_content'  => $mail['body'],
        'post_title'    => $mail['header']->subject,
        'post_type'     => 'my-email',
        'post_status'   => 'publish',
        'meta_input'    => array(
                'to'           => $mail['header']->toaddress,
                'email_date'    => $mail['header']->Date,   // add post meta as many as you want
            ),
       );
       wp_insert_post($post_array);
    }
    

I changed your class and added 1 more function to get a total number of emails. after that, I get email one by one and create a post using wp_insert_post()

Now you can read it using your code:

$args = array(
'post_type' => 'my-email',
);

$emails = new WP_query($args);

while($emails->have_posts()) {
$emails->the_post();

?>
<h3><?php the_title(); ?></h3>

I did not add an Excerpt but you can modify my code according to your need. Thank you.

9
  • Thanks a lot this worked. But every time I refresh my post page i.e faqpress-email. The inbox is filled with twice the number of emails. I have a total of 6 emails and when I refresh the post page it adds 12 posts automatically.
    – Rohit kc
    Dec 6, 2021 at 12:06
  • yes because this is code for the insert. We have to develop logic and check if the email exists in the database then do not run wp_insert_post(); function.
    – Ravi
    Dec 6, 2021 at 13:26
  • OK! I will look into it. But if you do have something you can help me with I will be grateful.
    – Rohit kc
    Dec 6, 2021 at 13:48
  • I have used one more line that is 'ticket_id; => $mail['header']->Msgno, inside meta input. Now before doing wp_insert_post($post_array); I want a if statement to check if the Msgno/ticket_id already exists and if it exists don't use it as a post type. How can I achieve that?
    – Rohit kc
    Dec 7, 2021 at 8:00
  • for this you have to write sql for example "SELECT * FROM post_meta where meta_key = 'ticket_id' and meta_value='$mail['header']->Msgno' "; or refer wordpress.stackexchange.com/questions/121154/… this link for WordPress style. if both exist than do not run wp_insert_post()
    – Ravi
    Dec 7, 2021 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.