32 from rapp_utilities
import RappUtilities
34 from rapp_platform_ros_communications.srv
import (
36 ReceiveEmailSrvResponse
39 from rapp_platform_ros_communications.msg
import (
50 receiveSrvTopic = rospy.get_param(
"rapp_email_receive_topic")
51 receiveSrv = rospy.Service(receiveSrvTopic, ReceiveEmailSrv, \
61 resp = ReceiveEmailSrvResponse()
64 RappUtilities.rapp_print(
'Request:\n' + str(req),
'DEBUG')
66 imapConn = self.
_connectImap(req.email, req.password, req.server, req.port)
67 except (imaplib.IMAP4.error, socket.error), err:
72 status, mailNum = imapConn.select()
73 if status.lower() !=
'OK'.lower():
74 RappUtilities.rapp_print(
"Requested mail folder not found",
'ERROR')
80 RappUtilities.rapp_print(
'# of email selected to fetch: ' + \
81 str(len(emailUIDs)),
'DEBUG')
82 except imaplib.IMAP4.error, err:
86 if len(emailUIDs) == 0:
87 RappUtilities.rapp_print(
'No emails retrieved')
92 if req.numberOfEmails != 0
and len(emailUIDs) > req.numberOfEmails:
93 emailUIDs = emailUIDs[ len(emailUIDs) - req.numberOfEmails : ]
98 for emailID
in emailUIDs:
99 emailData = self.
_fetchEmail(imapConn, emailID, emailPath, emailCounter)
100 resp.emails.append(emailData)
116 fetchStatus, data = imap.uid(
'fetch', emailID,
'(RFC822)' )
117 mail = email.message_from_string( data[0][1] )
120 emailPath = tempfile.mkdtemp( prefix = str(emailCounter) +
'_', \
124 bodyFD, bodyFilePath = tempfile.mkstemp( prefix=
'body_', \
128 'From: ' + str(mail[
'From']) +
'\n' + \
129 'To: ' + str(mail[
'To']) +
'\n' + \
130 'CC: ' + str(mail[
'cc']) +
'\n' + \
131 'Subject: ' + str(mail[
'Subject']) +
'\n' \
132 'Date: ' + mail[
'Date'] +
'\n\n' \
136 mailMsg.bodyPath = bodyFilePath
137 mailMsg.subject = str(mail[
'Subject'])
138 mailMsg.dateTime = str(mail[
'Date'])
139 mailMsg.sender = str(mail[
'From'])
140 mailMsg.receivers = []
141 for receiver
in str(mail[
'To']).
split(
','):
142 mailMsg.receivers.append(receiver.strip())
144 if mail[
'cc']
is not None:
145 for receiver
in str(mail[
'cc']).
split(
','):
146 mailMsg.receivers.append(receiver.strip())
147 mailMsg.attachmentPaths = []
149 attachmentCounter = 1
151 for part
in mail.walk():
152 if part.get_content_maintype() ==
'multipart':
154 if part.get_content_maintype() ==
'text':
156 if part.get(
'Content-Disposition')
is None and \
157 part.get_content_type() !=
'text/html':
158 os.write(bodyFD, part.get_payload( decode =
True ) )
159 os.write(bodyFD,
'\n' )
162 if part.get(
'Content-Disposition')
is None:
166 filename = part.get_filename()
168 filename =
'attachment-%03d' % attachmentCounter
169 attachmentCounter += 1
172 attachmentFD, attachmentPath = tempfile.mkstemp( prefix=filename +
"_", \
175 os.write(attachmentFD, part.get_payload( decode =
True ) )
176 os.close(attachmentFD)
177 mailMsg.attachmentPaths.append( attachmentPath )
189 basePath = os.path.join( os.environ[
'HOME'],
'rapp_platform_files',
'emails' )
191 if not os.path.exists( basePath ):
192 RappUtilities.rapp_print(
"Language temporary directory does not exist. " + \
194 os.makedirs( basePath )
196 username = email.split(
'@')[0]
198 finalPath = tempfile.mkdtemp( prefix=username +
'_', dir = basePath)
200 RappUtilities.rapp_print(
'Email receiver path: ' + finalPath,
'DEBUG')
204 atexit.register(shutil.rmtree, finalPath)
216 if req.requestedEmailStatus ==
'ALL':
217 requestedEmailStatus =
'ALL'
219 requestedEmailStatus =
'UNSEEN'
220 if req.requestedEmailStatus !=
'UNSEEN':
221 RappUtilities.rapp_print( \
222 'Wrong email status provided. ' + \
223 'See EmailReceiveSrv.srv for additional details. ' + \
224 'Falling back to default value: "UNSEEN"',
'WARN')
226 fromDate = toDate =
''
227 if req.fromDate != 0:
228 dateString = datetime.datetime.fromtimestamp(req.fromDate).strftime( \
230 fromDate =
' SINCE "' + dateString +
'"'
232 dateString = datetime.datetime.fromtimestamp(req.toDate).strftime( \
234 toDate =
' BEFORE "' + dateString +
'"'
236 searchQuery =
'(' + requestedEmailStatus + fromDate + toDate +
')'
237 RappUtilities.rapp_print(searchQuery,
'DEBUG')
240 searchStatus, msgIds = imap.uid(
'search',
None, searchQuery )
241 except imaplib.IMAP4.error, err:
242 RappUtilities.rapp_print(
"Could not perform IMPA search. Query: " + \
243 searchQuery,
'ERROR')
244 RappUtilities.rapp_print( err,
'ERROR')
247 return msgIds[0].
split()
267 socket.setdefaulttimeout(5)
268 if port
is not None and port !=
'':
269 imap = imaplib.IMAP4_SSL( server, port )
271 imap = imaplib.IMAP4_SSL( server )
272 except (imaplib.IMAP4.error, socket.error), err:
273 RappUtilities.rapp_print( \
274 "Could not establish a connection to the requested IMAP server: " + \
275 server +
' port: ' + port,
'ERROR')
276 RappUtilities.rapp_print( err,
'ERROR')
280 imap.login( email, password )
281 except imaplib.IMAP4.error, err:
282 RappUtilities.rapp_print( \
283 "Could not login to the requested IMAP server: " + \
285 RappUtilities.rapp_print( err,
'ERROR')
291 if __name__ ==
'__main__':
292 print(
'Implements server for EmailReceiverSrv. Not supposed to' + \
293 ' be called directly')
def receiveEmailSrvCallback
The callback to receive specified mails from users email account.
def _selectEmails
Fetch the emails that match the requests criteria.
def _initializePath
Create a temporary path for the user emails.
def _fetchEmail
Fetch specified email's data.
Fetches emails from user's email account.
def _connectImap
Create an IMAP connection to the server.
std::vector< std::string > split(std::string str, std::string sep)
Splits string by delimiter.