我正在运行以下代码以使用IMAP PHP extension检索电子邮件:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h> /* for atoi */
char *msg = "Very long message";
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sock, n;
unsigned short port;
struct sockaddr_in server;
struct hostent *hp;
char buffer[1024];
if (argc != 3) {
printf("Usage: %s server port\n", argv[0]);
exit(1);
}
sock= socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) error("Opening socket");
server.sin_family = AF_INET;
hp = gethostbyname(argv[1]);
if (hp==NULL) error("Unknown host");
memcpy((char *)&server.sin_addr,(char *)hp->h_addr,
hp->h_length);
port = (unsigned short)atoi(argv[2]);
server.sin_port = htons(port);
if (connect(sock, (struct sockaddr *)&server, sizeof server) < 0)
error("Connecting");
n = send(sock, msg, strlen(msg),0);
printf("sent %d bytes\n", n);
if (n < strlen(msg))
error("Writing to socket");
n = recv(sock, buffer, 1023,0);
if (n < 1) error("reading from socket");
buffer[n]='\0';
printf("The message from the server is %s\n",buffer);
if (close(sock) < 0) error("closing");
printf("Client terminating\n");
return 0;
}
将<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'blah@gmail.com';
$password = 'blah';
$inbox = imap_open($hostname,$username,$password);
$emails = imap_search($inbox,'ALL');
if ($emails) {
foreach($emails as $emailNumber) {
$overview = imap_fetch_overview($inbox,$emailNumber,0);
$message = imap_fetchbody($inbox,$emailNumber,"1");
echo $overview[0]->from;
echo $message;
}
}
imap_close($inbox);
?>
imap_fetchbody()
参数设置为section
后,我会收到包含标题和HTML的完整电子邮件。 http://pastebin.com/np84rG7r
但是,当将参数更改为1
以便将消息标识为HTML时,它不会返回任何内容。
为什么会这样?
我已经制作了一小段代码来手动完成工作,直到我找到它无法正常工作的原因:
1.2
答案 0 :(得分:0)
不幸的是,imap_fetchbody
的部件号取决于您的邮件是否带有html,以及是否带有附件。当您收到纯文本邮件时,则需要使用1
而不是1.2
。
要阅读完整的悲剧,我建议https://www.php.net/manual/en/function.imap-fetchbody.php#89002
确保您始终获得体内含量的一种俗气的方法是
$message = imap_fetchbody($inbox,$emailNumber,1.2);
if(empty($bodyText)){
$message = imap_fetchbody($inbox,$emailNumber,1);
}