백엔드 개발 파이썬 튜토리얼 Python에서 제때에 새 이메일을 받는 방법에 대한 코드 예제

Python에서 제때에 새 이메일을 받는 방법에 대한 코드 예제

Aug 10, 2017 pm 01:58 PM
python 성취하다 우편

이 기사에서는 Python 실시간 쿼리 사서함 및 이메일 획득 관련 작업 기술을 포함하여 새로운 이메일에 적시에 액세스할 수 있는 Python 프로그래밍 방법을 주로 소개합니다. 도움이 필요한 친구는 이를 참조할 수 있습니다

이 기사의 예에서는 새로운 이메일에 적시에 액세스할 수 있는 Python 프로그래밍. 참고할 수 있도록 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

#-*- encoding: utf-8 -*-

import sys

import locale

import poplib

from email import parser

import email

import string

import mysql.connector

import traceback

import datetime

from mysql.connector import errorcode

import time

import re

reload(sys);

sys.setdefaultencoding('utf8');

# 确定运行环境的encoding

__g_codeset = sys.getdefaultencoding()

if "ascii"==__g_codeset:

  __g_codeset = 'utf8';

#

def object2double(obj):

  if(obj==None or obj==""):

    return 0

  else:

    return float(obj)

  #end if

#

def getMailIndex():

  file = open('mailindex.txt',"r");

  lines = file.readlines();

  file.close();

  return int(lines[0]);

#

def setMailIndex(index):

  f = open('mailindex.txt', 'w');

  f.write(index);

  f.close();

#

def utf8_to_mbs(s):

  return s.decode("utf-8").encode(__g_codeset)

#

def utf8_to_gbk(s):

  return s.decode("utf-8").encode('gb2312')

#

def mbs_to_utf8(s):

  return s.decode(__g_codeset).encode("utf-8")

#

def gbk_to_utf8(s):

  return s.decode('gb2312').encode("utf-8")

#

def _queryQuick(cu,sql,tuple):

  try:

    cu.execute(sql,tuple);

    rows = []

    for row in cu:

      rows.append(row)

    #

    return rows

  except:

    print(traceback.format_exc())

  #end

#

#获取信息

def _queryRows(cu,sql):

  try:

    cu.execute(sql)

    rows = []

    for row in cu:

      rows.append(row)

    #

    return rows

  except:

    print(traceback.format_exc())

  #end

#

#是否有新邮件

global hasNewMail;

hasNewMail=True;

#全局已读的邮件数量

global globalMailReaded;

globalMailReaded=getMailIndex()+1;

#获取新邮件

def getNewMail(conn2,cur2):

  try:

    global hasNewMail;

    global globalMailReaded;

    conn2.commit();

    rows=_queryRows(cur2,"select count(*) as message_count from hm_messages where messageaccountid=1");

    message_count=rows[0][0];

    if(hasNewMail):

      print('read mailindex.txt')

      globalMailReaded=getMailIndex()+1;

    #end if

    if(message_count<=globalMailReaded):

      hasNewMail=False;

      #print(&#39;Did not receive new mail,continue wait...&#39;)

      return None;#没新邮件,直接返回

    #end if

    #登陆邮箱

    host = &#39;127.0.0.1&#39;

    username = &#39;username@myserver.net&#39;

    password = &#39;password&#39;

    pop_conn = poplib.POP3(host)

    #print pop_conn.getwelcome()

    pop_conn.user(username);

    pop_conn.pass_(password);

    #Get messages from server:

    messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]

    # Concat message pieces:

    messages = ["\n".join(mssg[1]) for mssg in messages]

    #Parse message intom an email object:

    messages = [parser.Parser().parsestr(mssg) for mssg in messages]

    print("get new mail!");

    print pop_conn.stat()

    print(&#39;%s readed mail count is %d,all mail count is: %d&#39;%(datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"),globalMailReaded,len(messages)))

    message = messages[globalMailReaded];

    subject = message.get(&#39;subject&#39;)

    h = email.Header.Header(subject)

    dh = email.Header.decode_header(h)

    #subject = unicode(dh[0][0], dh[0][1]).encode(&#39;utf8&#39;)

    #print >> f, "Date: ", message["Date"]

    #print >> f, "From: ", email.utils.parseaddr(message.get(&#39;from&#39;))[1]

    #print >> f, "To: ", email.utils.parseaddr(message.get(&#39;to&#39;))[1]

    #print >> f, "Subject: ", subject

    j = 0

    for part in message.walk():

      j = j + 1

      fileName = part.get_filename()

      contentType = part.get_content_type()

      mycode=part.get_content_charset();

      # 保存附件

      if fileName:

        pass;

      elif contentType == &#39;text/plain&#39;:# or contentType == &#39;text/html&#39;:

        #保存正文

        data = part.get_payload(decode=True)

        content=str(data);

        if mycode==&#39;gb2312&#39;:

          content= gbk_to_utf8(content)

        #end if

        content=content.replace(u&#39;\u200d&#39;,&#39;&#39;);

        setMailIndex(str(globalMailReaded));

        hasNewMail=True;

        pop_conn.quit();

        return (content,email.utils.parseaddr(message.get(&#39;from&#39;))[1]);

      #end if

    #end for

  except:

    print("search hmailserver fail,try again");

    return None;

  finally:

    pass;

  #end try

#end def

#连接数据库

conn2 = mysql.connector.connect(user=&#39;root&#39;, password=&#39;password&#39;,host=&#39;127.0.0.1&#39;,database=&#39;hmailserver&#39;,charset=&#39;gb2312&#39;);

cur2 = conn2.cursor();

#只要收到电子邮件,就把这个事件记录在事件库中

#现在就是循环查询邮箱,如果有新邮件就读取,并查询关键词库

while(True):

  mailtuple=getNewMail(conn2,cur2);

  if(mailtuple==None):

    #print(&#39;Did not search MySQL,continue loop...&#39;)

    time.sleep(0.5)

    continue;

  #end if

  (article,origin)=mailtuple;

#end while

로그인 후 복사

위 내용은 Python에서 제때에 새 이메일을 받는 방법에 대한 코드 예제의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP와 Python : 다른 패러다임이 설명되었습니다 PHP와 Python : 다른 패러다임이 설명되었습니다 Apr 18, 2025 am 12:26 AM

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP와 Python 중에서 선택 : 가이드 PHP와 Python 중에서 선택 : 가이드 Apr 18, 2025 am 12:24 AM

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

숭고한 코드 파이썬을 실행하는 방법 숭고한 코드 파이썬을 실행하는 방법 Apr 16, 2025 am 08:48 AM

Sublime 텍스트로 Python 코드를 실행하려면 먼저 Python 플러그인을 설치 한 다음 .py 파일을 작성하고 코드를 작성한 다음 CTRL B를 눌러 코드를 실행하면 콘솔에 출력이 표시됩니다.

PHP와 Python : 그들의 역사에 깊은 다이빙 PHP와 Python : 그들의 역사에 깊은 다이빙 Apr 18, 2025 am 12:25 AM

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

Python vs. JavaScript : 학습 곡선 및 사용 편의성 Python vs. JavaScript : 학습 곡선 및 사용 편의성 Apr 16, 2025 am 12:12 AM

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

Golang vs. Python : 성능 및 확장 성 Golang vs. Python : 성능 및 확장 성 Apr 19, 2025 am 12:18 AM

Golang은 성능과 확장 성 측면에서 Python보다 낫습니다. 1) Golang의 컴파일 유형 특성과 효율적인 동시성 모델은 높은 동시성 시나리오에서 잘 수행합니다. 2) 해석 된 언어로서 파이썬은 천천히 실행되지만 Cython과 같은 도구를 통해 성능을 최적화 할 수 있습니다.

vscode에서 코드를 작성하는 위치 vscode에서 코드를 작성하는 위치 Apr 15, 2025 pm 09:54 PM

Visual Studio Code (VSCODE)에서 코드를 작성하는 것은 간단하고 사용하기 쉽습니다. vscode를 설치하고, 프로젝트를 만들고, 언어를 선택하고, 파일을 만들고, 코드를 작성하고, 저장하고 실행합니다. VSCODE의 장점에는 크로스 플랫폼, 무료 및 오픈 소스, 강력한 기능, 풍부한 확장 및 경량 및 빠른가 포함됩니다.

메모장으로 파이썬을 실행하는 방법 메모장으로 파이썬을 실행하는 방법 Apr 16, 2025 pm 07:33 PM

메모장에서 Python 코드를 실행하려면 Python 실행 파일 및 NPPEXEC 플러그인을 설치해야합니다. Python을 설치하고 경로를 추가 한 후 nppexec 플러그인의 명령 "Python"및 매개 변수 "{current_directory} {file_name}"을 구성하여 Notepad의 단축키 "F6"을 통해 Python 코드를 실행하십시오.

See all articles