在 gmail 中获取发件人邮件-api
Get sender mail in gmail-api
我正在尝试通过 gmail-api 开发人员 guide.The gmail-api 中的消息部分找出它 - api 不包含有关发件人的任何详细信息,感谢您的帮助。
您可以先 list messages,获取 id
条消息。
要求:
GET https://www.googleapis.com/gmail/v1/users/me/messages
响应:
{
"messages": [
{
"id": "1504f80fcf4ceb5f",
"threadId": "1504f80fcf4ceb5f"
}, ...
]
}
然后,您可以通过 getting the actual message.
在第二个请求中询问这些邮件的发件人
要求:
format = metadata
metadataHeaders = From
fields = payload/headers
GET https://www.googleapis.com/gmail/v1/users/me/messages/1504f80fcf4ceb5f?format=metadata&metadataHeaders=From&fields=payload%2Fheaders
响应:
{
"payload": {
"headers": [
{
"name": "From",
"value": "YouTube <noreply@youtube.com>"
}
]
}
}
Ok I finally did it.Get message payload and then get headers from payload loop through the headers with name "from"
format of header is of the form header=[name:"somename" value:"somevalue"]
here is my code hope it helps someone
private List<MessageReader> getDataFromApi() throws IOException {
String user = "me";
List<MessageReader> labels = new ArrayList<MessageReader>();
ListMessagesResponse listResponse = mActivity.mService.users().messages().list(user).setQ(query).execute();
//int i=0;
for (Message label : listResponse.getMessages()) {
Message m = mActivity.mService.users().messages().get(user, label.getId()).execute();
String a ="";
try{
List<MessagePart> parts =m.getPayload().getParts();
List<MessagePartHeader> headers = m.getPayload().getHeaders();
MessageReader mreader = readParts(parts);
mreader.setDate(m.getInternalDate());
for(MessagePartHeader header:headers){
String name = header.getName();
if(name.equals("From")||name.equals("from")){
mreader.setSender(header.getValue());
break;
}
}
labels.add(mreader);
}catch(Exception e){
a+="The following error occurred:\n" +
e.getMessage();
}
}
return labels;//extractData(labels);
}
private MessageReader readParts(List<MessagePart> parts){
MessageReader mreader = new MessageReader();
int cnt =0;
for(MessagePart part:parts){
try{
String mime = part.getMimeType();
if(mime.contentEquals("text/plain")){
String s = new String(Base64.decodeBase64(part.getBody().getData().getBytes()));
mreader.setText(s);
}else if(mime.contentEquals("text/html")){
String s = new String(Base64.decodeBase64(part.getBody().getData().getBytes()));
mreader.setHtml(s);
}else if(mime.contentEquals("multipart/alternative")){
List<MessagePart> subparts =part.getParts();
MessageReader subreader = readParts(subparts);
mreader.setText(subreader.getText());
mreader.setHtml(subreader.getHtml());
}else if(mime.contentEquals("application/octet-stream")){
cnt++;
mreader.setNo_of_files(cnt);
}
}catch(Exception e){
// get file here
}
}
return mreader;
}
public class MessageReader {
private String text;
private String html;
int no_of_files;
private String sender;
private long date;
// file data to be made
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
public int getNo_of_files() {
return no_of_files;
}
public void setNo_of_files(int no_of_files) {
this.no_of_files = no_of_files;
}
}
假设您已经使用 ListMessagesResponse 获得了消息 ID,
这是获取发件人的方法,即 From field:
public String getFrom(String userId, String messageId) throws IOException {
Message message = mService.users().messages().get(userId, messageId).execute();
List<MessagePartHeader> headers = message.getPayload().getHeaders();
String from="";
for (MessagePartHeader header:headers){
if(header.getName().equals("From")){
from=header.getValue();
break;
}
}
return from;
}
从文档我们可以知道 Users.messages 会给我们的消息具有以下属性
{
"id": string,
"threadId": string,
"labelIds": [
string
],
"snippet": string,
"historyId": unsigned long,
"internalDate": long,
"payload": {
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
"name": string,
"value": string
}
],
"body": users.messages.attachments Resource,
"parts": [
(MessagePart)
]
},
"sizeEstimate": integer,
"raw": bytes
}
从上面的属性我们可以使用payload.headers[]
知道发件人邮件。
payload.headers[]
将包含形式为 {"name":string , "value":string}
的字典数组。要获取发件人的邮件,我们必须找到带有 name == 'From'
的字典,其对应的 value
将为我们提供发件人的邮件
我附上我的 python 代码以供参考
#Call the Gmail API
#Before calling the API you have to create service using User credentials
results = service.users().messages().list(userId='me',labelIds = ['INBOX']).execute()
msgs = results.get('messages',[])
for msg in msgs:
mg = service.users().messages().get(userId='me', id=msg['id']).execute()
msg_headers = mg['payload']['headers']
for k in range(len(msg_headers)):
if msg_headers[k]['name'] == 'From':
print(msg_headers[k]['value'])
print("\n")
我正在尝试通过 gmail-api 开发人员 guide.The gmail-api 中的消息部分找出它 - api 不包含有关发件人的任何详细信息,感谢您的帮助。
您可以先 list messages,获取 id
条消息。
要求:
GET https://www.googleapis.com/gmail/v1/users/me/messages
响应:
{
"messages": [
{
"id": "1504f80fcf4ceb5f",
"threadId": "1504f80fcf4ceb5f"
}, ...
]
}
然后,您可以通过 getting the actual message.
在第二个请求中询问这些邮件的发件人要求:
format = metadata
metadataHeaders = From
fields = payload/headers
GET https://www.googleapis.com/gmail/v1/users/me/messages/1504f80fcf4ceb5f?format=metadata&metadataHeaders=From&fields=payload%2Fheaders
响应:
{
"payload": {
"headers": [
{
"name": "From",
"value": "YouTube <noreply@youtube.com>"
}
]
}
}
Ok I finally did it.Get message payload and then get headers from payload loop through the headers with name "from"
format of header is of the form header=[name:"somename" value:"somevalue"]
here is my code hope it helps someone
private List<MessageReader> getDataFromApi() throws IOException {
String user = "me";
List<MessageReader> labels = new ArrayList<MessageReader>();
ListMessagesResponse listResponse = mActivity.mService.users().messages().list(user).setQ(query).execute();
//int i=0;
for (Message label : listResponse.getMessages()) {
Message m = mActivity.mService.users().messages().get(user, label.getId()).execute();
String a ="";
try{
List<MessagePart> parts =m.getPayload().getParts();
List<MessagePartHeader> headers = m.getPayload().getHeaders();
MessageReader mreader = readParts(parts);
mreader.setDate(m.getInternalDate());
for(MessagePartHeader header:headers){
String name = header.getName();
if(name.equals("From")||name.equals("from")){
mreader.setSender(header.getValue());
break;
}
}
labels.add(mreader);
}catch(Exception e){
a+="The following error occurred:\n" +
e.getMessage();
}
}
return labels;//extractData(labels);
}
private MessageReader readParts(List<MessagePart> parts){
MessageReader mreader = new MessageReader();
int cnt =0;
for(MessagePart part:parts){
try{
String mime = part.getMimeType();
if(mime.contentEquals("text/plain")){
String s = new String(Base64.decodeBase64(part.getBody().getData().getBytes()));
mreader.setText(s);
}else if(mime.contentEquals("text/html")){
String s = new String(Base64.decodeBase64(part.getBody().getData().getBytes()));
mreader.setHtml(s);
}else if(mime.contentEquals("multipart/alternative")){
List<MessagePart> subparts =part.getParts();
MessageReader subreader = readParts(subparts);
mreader.setText(subreader.getText());
mreader.setHtml(subreader.getHtml());
}else if(mime.contentEquals("application/octet-stream")){
cnt++;
mreader.setNo_of_files(cnt);
}
}catch(Exception e){
// get file here
}
}
return mreader;
}
public class MessageReader {
private String text;
private String html;
int no_of_files;
private String sender;
private long date;
// file data to be made
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
public int getNo_of_files() {
return no_of_files;
}
public void setNo_of_files(int no_of_files) {
this.no_of_files = no_of_files;
}
}
假设您已经使用 ListMessagesResponse 获得了消息 ID, 这是获取发件人的方法,即 From field:
public String getFrom(String userId, String messageId) throws IOException {
Message message = mService.users().messages().get(userId, messageId).execute();
List<MessagePartHeader> headers = message.getPayload().getHeaders();
String from="";
for (MessagePartHeader header:headers){
if(header.getName().equals("From")){
from=header.getValue();
break;
}
}
return from;
}
从文档我们可以知道 Users.messages 会给我们的消息具有以下属性
{
"id": string,
"threadId": string,
"labelIds": [
string
],
"snippet": string,
"historyId": unsigned long,
"internalDate": long,
"payload": {
"partId": string,
"mimeType": string,
"filename": string,
"headers": [
{
"name": string,
"value": string
}
],
"body": users.messages.attachments Resource,
"parts": [
(MessagePart)
]
},
"sizeEstimate": integer,
"raw": bytes
}
从上面的属性我们可以使用payload.headers[]
知道发件人邮件。
payload.headers[]
将包含形式为 {"name":string , "value":string}
的字典数组。要获取发件人的邮件,我们必须找到带有 name == 'From'
的字典,其对应的 value
将为我们提供发件人的邮件
我附上我的 python 代码以供参考
#Call the Gmail API
#Before calling the API you have to create service using User credentials
results = service.users().messages().list(userId='me',labelIds = ['INBOX']).execute()
msgs = results.get('messages',[])
for msg in msgs:
mg = service.users().messages().get(userId='me', id=msg['id']).execute()
msg_headers = mg['payload']['headers']
for k in range(len(msg_headers)):
if msg_headers[k]['name'] == 'From':
print(msg_headers[k]['value'])
print("\n")