Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# (c) Stefan Countryman, 2019 

2 

3""" 

4Utility functions and abstract ``FileHandler`` bases for communicating via 

5email. 

6""" 

7 

8# needed to make this a package, not a module, to avoid an ImportMismatchError: 

9# https://stackoverflow.com/questions/44067609 

10 

11from abc import ABC, abstractproperty 

12import datetime 

13# TODO use sendgrid API 

14from llama.utils import ( 

15 send_email, 

16) 

17from llama.com.utils import UploadReceipt 

18 

19utcnow = datetime.datetime.utcnow 

20 

21 

22# pylint: disable=too-many-ancestors,duplicate-bases 

23class EmailReceipt(UploadReceipt): 

24 """ 

25 A log file created as a side effect of emailing some text (e.g. for 

26 submission of GCN notices or circulars). This is sufficiently formulaic 

27 that only an uploaded file, recipient list, and (optional) veto condition 

28 must be specified in each subclass. 

29 """ 

30 

31 @abstractproperty 

32 def recipients(self): 

33 """A list of email addresses that should receive this email.""" 

34 

35 @abstractproperty 

36 def subject(self): 

37 """A subject line for this email.""" 

38 

39 @property 

40 def send_as_attachment(self): 

41 """If this returns True, the UPLOAD will be submitted as an 

42 email attachment rather than as the body of the email, e.g. for PDF or 

43 image files. Returns False unless overridden by a subclass.""" 

44 return False 

45 

46 def _generate(self): # pylint: disable=arguments-differ 

47 # # based off of https://gist.github.com/stefco/0b40511e62f5615371f25746af47d52e 

48 # username, _, password = netrc().authenticators("gmail.com") 

49 # if not username: 

50 # raise IOError("Can't find a username for ligo.org in ~/.netrc.") 

51 # if not password: 

52 # raise IOError("Can't find a password for ligo.org in ~/.netrc.") 

53 # with SMTP('smtp.gmail.com', 587) as server: 

54 # server.starttls() 

55 # server.login(username, password) 

56 # body = '\r\n'.join(['To: ' + ', '.join(self.recipients), 

57 # 'From: ' + username, 

58 # 'Subject: ' + self.subject, 

59 # '', TEXT]) 

60 # try: 

61 # server.sendmail(username, self.recipients, body) 

62 # LOGGER.info('Email sent.') 

63 with open(self.fullpath, 'w') as outf: 

64 outf.write('{} sending at {}\n'.format(self.FILENAME, utcnow())) 

65 outf.write('subject: {}'.format(self.subject)) 

66 outf.write('recipients: {}'.format(self.recipients)) 

67 if self.send_as_attachment: 

68 outf.write('sending as attachment.') 

69 send_email(self.subject, self.recipients, 

70 body="{} attached.".format(self.UPLOAD.FILENAME), 

71 attachments=self.UPLOAD(self).fullpath) 

72 else: 

73 outf.write('sending as body.') 

74 with self.UPLOAD(self).open() as body: 

75 send_email(self.subject, self.recipients, body=body) 

76 outf.write('mail command succeeded.\n')