├── .example.env ├── .gitignore ├── AUTHORS ├── Dockerfile ├── LICENSE ├── README.md ├── commands ├── __init__.py ├── account.py ├── email.py ├── generic.py └── login.py ├── config └── loadConfig.py ├── docker-compose.yml ├── img ├── notmail_bot.png ├── notmail_bot.svg └── notmail_bot_license.txt ├── my-config ├── .empty └── config_example.ini ├── notmail_bot.py ├── repository ├── account.py ├── email_server.py ├── repository.py └── user.py ├── requirements.txt ├── services ├── __init__.py └── email.py ├── tests ├── __init__.py ├── accountTest.py ├── emailServerTest.py └── userTest.py └── utils ├── imap.py ├── populateDatabase.py ├── scheduler.py └── telegram.py /.example.env: -------------------------------------------------------------------------------- 1 | ## This is the example .env file. Feel free to modify and rename to .env 2 | 3 | ## The bot token. Please talk with @BotFather and copy from APIToken 4 | TELEGRAM_TOKEN= 5 | 6 | ## Your username or alias of telegram. 7 | ## TELEGRAM_ADMIN_USERNAME or TELEGRAM_ADMIN_USER_ID required. 8 | TELEGRAM_ADMIN_USERNAME= 9 | 10 | ## Your user_id of telegram. NOT USERNAME or alias. If you don't know, you can skip it. 11 | ## TELEGRAM_ADMIN_USERNAME or TELEGRAM_ADMIN_USER_ID required. 12 | #TELEGRAM_ADMIN_USER_ID= 13 | 14 | ## Path to database. By default, It is save in `config/notmail_bot.json` 15 | #TMAIL_DB_PATH= 16 | 17 | ## Default time between mail checks (in seconds). By default it is checked every 4 minutes 18 | #TMAIL_DEFAULT_REFRESH_TIME= 19 | 20 | ## Define the log level. By default it is configure to INFO. 21 | #TMAIL_LOG_LEVEL= 22 | 23 | ## Path to save the logs. By default it is unactive. 24 | #TMAIL_LOG_PATH= 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # KDE 104 | .directory 105 | *.md.backup 106 | 107 | # pycharm 108 | .idea/ 109 | 110 | config/tmail-bot.json 111 | config/tmail-bot.log 112 | config/myconfig.ini 113 | 114 | config/notmail_bot.json 115 | config/notmail_bot.log 116 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | The following people contribute or have contributed 2 | to the Notmail Bot project (sorted alphabetically): 3 | 4 | Juan Ramón Rodríguez Rosado (github.com/juanrarodriguez18) 5 | Manuel Fco. López Ruiz (github.com/ManuelLR) 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.6-alpine 2 | LABEL maintainer="@ManuelLR " 3 | 4 | WORKDIR /usr/src/bot 5 | 6 | COPY requirements.txt ./ 7 | RUN pip install --no-cache-dir -r requirements.txt 8 | 9 | COPY . . 10 | 11 | CMD [ "python", "./notmail_bot.py" ] 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Notmail Bot 2 | 3 | 4 | > Telegram bot that acts as an email client. 5 | 6 | **V.0.1.0** 7 | 8 | # Usage Preview 9 | _Work in progress_ 10 | 11 | # Features 12 | 13 | - Auto check email account and notify news. 14 | - Friendly interface. 15 | - Multiple email accounts. 16 | - Compatible with IMAP protocol. (More in the future). 17 | - Read email on Telegram, mark as read/unread, archive/delete and much more. 18 | 19 | # Basic configuration 20 | First of all, we need to know our `username` and the `bot_token`. The `username` could be configure in your Telegram app settings (also known as `alias`). To get the`bot_token` is necessary to speak with the [@BotFather](https://telegram.me/BotFather) and introduce the `/newbot` command. It will ask all necesary data and finally, it will give to you the `bot_token` also called `API Token`. 21 | 22 | # Launch 23 | We can launch in several ways: 24 | - [Docker Compose](./README.md#docker-compose) **(recomended)** 25 | - [Docker](./README.md#docker) 26 | - [Python](./README.md#python) 27 | 28 | ### Docker Compose 29 | To use [docker-compose](https://docs.docker.com/compose/overview/) you need to install on your computer [Docker-CE](https://docs.docker.com/) and [Docker-compose](https://docs.docker.com/compose/install/). 30 | 31 | Before running it you need to enter the variables in the new file called `.env`. 32 | 33 | ``` 34 | cp .example.env .env 35 | nano .env 36 | ``` 37 | 38 | Finally, we execute the next command and can start to talk with the bot: 39 | 40 | ``` 41 | docker-compose up -d 42 | ``` 43 | 44 | If we update the code, you only need to update it (`git pull`) and relaunch docker compose with the following command: 45 | 46 | ``` 47 | git pull 48 | docker-compose up -d --build 49 | ``` 50 | 51 | ### Docker 52 | 53 | ```bash 54 | sudo docker build -t notmail_bot . 55 | sudo docker run -d --name Notmail_bot \ 56 | --restart always \ 57 | --env-file .env \ 58 | manuellr/notmail_bot 59 | ``` 60 | 61 | 62 | ### Python 63 | ```bash 64 | pip install -r requirements.txt 65 | python notmail_bot.py --config_path my-config/my_config.ini 66 | ``` 67 | 68 | 69 | # License 70 | - The main code is licensed under [GPLv3](./LICENSE) 71 | - The logo of Notmail is licensed under [Free Art License v1.3](./img/notmail_bot_license.txt) 72 | 73 | You can consult the contributors in the [AUTHORS file](./AUTHORS) or see the contributors of a specific file executing the next script: 74 | ```bash 75 | git blame -C -C -M -- FILE_TO_CONSULT | \ 76 | sed -e 's/[^(]*(\([^0-9]*\).*/\1/' -e 's/[\t ]*$//' | \ 77 | sort | uniq -c | sort -nr 78 | ``` 79 | -------------------------------------------------------------------------------- /commands/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | from telegram.ext import CommandHandler, CallbackQueryHandler, ConversationHandler, MessageHandler, \ 18 | RegexHandler, Filters 19 | 20 | from commands.generic import start, help, error, button 21 | from commands.email import view_email, view_detailed_email, mark_read_email, mark_unread_email,\ 22 | help_email, archive_email, label_list_email, delete_email 23 | from commands.account import account_options, account_servers, add_gmail_account, add_outlook_account,\ 24 | add_other_account, add_gmail_username_account, add_password_account, add_refresh_time_account, \ 25 | cancel, modify_account, modify_password, modify_account_password, modify_password_password, \ 26 | modify_refresh_time, modify_account_refresh_time, modify_refresh_time_refresh_time, remove_account,\ 27 | remove_account_account 28 | 29 | 30 | def load_dispatcher(dispatcher): 31 | dispatcher.add_handler(CommandHandler('start', start)) 32 | dispatcher.add_handler(CommandHandler('help', help)) 33 | dispatcher.add_handler(CallbackQueryHandler(button, pattern="(\/start\/).+")) 34 | 35 | # EMAIL 36 | dispatcher.add_handler(CallbackQueryHandler(view_detailed_email, pattern="(\/email\/view\/).+")) 37 | dispatcher.add_handler(CallbackQueryHandler(view_email, pattern="(\/email\/back\/).+")) 38 | dispatcher.add_handler(CallbackQueryHandler(mark_read_email, pattern="(\/email\/mark_read\/).+")) 39 | dispatcher.add_handler(CallbackQueryHandler(mark_unread_email, pattern="(\/email\/mark_unread\/).+")) 40 | dispatcher.add_handler(CallbackQueryHandler(archive_email, pattern="(\/email\/archive\/).+")) 41 | dispatcher.add_handler(CallbackQueryHandler(label_list_email, pattern="(\/email\/label_l\/).+")) 42 | dispatcher.add_handler(CallbackQueryHandler(delete_email, pattern="(\/email\/delete\/).+")) 43 | 44 | dispatcher.add_handler(CallbackQueryHandler(help_email, pattern="(\/email\/help)")) 45 | 46 | dispatcher.add_handler(CommandHandler('list_folders', help)) 47 | 48 | # ACCOUNTS 49 | dispatcher.add_handler(CallbackQueryHandler(account_options, pattern="(\/account\/options)")) 50 | dispatcher.add_handler(CallbackQueryHandler(account_servers, pattern="(\/account\/add\/servers)$")) 51 | dispatcher.add_handler(CallbackQueryHandler(modify_account, pattern="(\/account\/modify)$")) 52 | 53 | # ADD GMAIL ACCOUNT 54 | ACCOUNT, PASSWORD, REFRESH_TIME = range(3) 55 | conv_gmail_handler = ConversationHandler( 56 | entry_points=[CallbackQueryHandler(add_gmail_account, pattern="(\/account\/add\/servers\/gmail)")], 57 | states={ 58 | ACCOUNT: [RegexHandler('^.*?@.*?\..*$', add_gmail_username_account, pass_user_data=True)], 59 | PASSWORD: [MessageHandler(Filters.text, add_password_account, pass_user_data=True)], 60 | REFRESH_TIME: [MessageHandler(Filters.text, add_refresh_time_account, pass_user_data=True)] 61 | }, 62 | fallbacks=[CommandHandler('cancel', cancel)] 63 | ) 64 | dispatcher.add_handler(conv_gmail_handler) 65 | dispatcher.add_error_handler(error) 66 | 67 | # MODIFY PASSWORD 68 | ACCOUNT, PASSWORD = range(2) 69 | conv_modify_password = ConversationHandler( 70 | entry_points=[CallbackQueryHandler(modify_password, pattern="(\/account\/modify\/password)")], 71 | states={ 72 | ACCOUNT: [RegexHandler('^.*?@.*?\..*$', modify_account_password, pass_user_data=True)], 73 | PASSWORD: [MessageHandler(Filters.text, modify_password_password, pass_user_data=True)] 74 | }, 75 | fallbacks=[CommandHandler('cancel', cancel)] 76 | ) 77 | dispatcher.add_handler(conv_modify_password) 78 | dispatcher.add_error_handler(error) 79 | 80 | # MODIFY REFRESH_TIME 81 | ACCOUNT, REFRESH_TIME = range(2) 82 | conv_modify_refresth_time = ConversationHandler( 83 | entry_points=[CallbackQueryHandler(modify_refresh_time, pattern="(\/account\/modify\/refresh_time)")], 84 | states={ 85 | ACCOUNT: [RegexHandler('^.*?@.*?\..*$', modify_account_refresh_time, pass_user_data=True)], 86 | REFRESH_TIME: [MessageHandler(Filters.text, modify_refresh_time_refresh_time, pass_user_data=True)] 87 | }, 88 | fallbacks=[CommandHandler('cancel', cancel)] 89 | ) 90 | dispatcher.add_handler(conv_modify_refresth_time) 91 | dispatcher.add_error_handler(error) 92 | 93 | # REMOVE ACCOUNT 94 | ACCOUNT = range(1) 95 | conv_remove_account = ConversationHandler( 96 | entry_points=[CallbackQueryHandler(remove_account, pattern="(\/account\/remove)")], 97 | states={ 98 | ACCOUNT: [RegexHandler('^.*?@.*?\..*$', remove_account_account)] 99 | }, 100 | fallbacks=[CommandHandler('cancel', cancel)] 101 | ) 102 | dispatcher.add_handler(conv_remove_account) 103 | dispatcher.add_error_handler(error) 104 | -------------------------------------------------------------------------------- /commands/account.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 18 | from telegram.ext import ConversationHandler 19 | from repository.repository import DBC 20 | from repository.account import Account 21 | 22 | import logging 23 | 24 | ACCOUNT, PASSWORD, REFRESH_TIME = range(3) 25 | 26 | 27 | #Account Options 28 | 29 | def account_options(bot, update): 30 | query = update.callback_query 31 | 32 | keyboard = [[InlineKeyboardButton("Add Account", callback_data='/account/add/servers')], 33 | [InlineKeyboardButton("Modify Account", callback_data='/account/modify'), 34 | InlineKeyboardButton("Remove Account", callback_data='/account/remove')]] 35 | 36 | reply_markup = InlineKeyboardMarkup(keyboard) 37 | 38 | query.message.reply_text('What do you want to do with Accounts?', reply_markup=reply_markup) 39 | logging.debug(query.message.chat_id) 40 | 41 | 42 | def account_servers(bot, update): 43 | query = update.callback_query 44 | keyboard = [[InlineKeyboardButton("GMAIL", callback_data='/account/add/servers/gmail')], 45 | [InlineKeyboardButton("OUTLOOK - (NOT AVAILABLE)", callback_data='/account/add/servers/outlook')], 46 | [InlineKeyboardButton("OTHER - (NOT AVAILABLE)", callback_data='/account/add/servers/other')]] 47 | 48 | reply_markup = InlineKeyboardMarkup(keyboard) 49 | 50 | query.message.reply_text('On which server do you want to add the Account?', reply_markup=reply_markup) 51 | logging.debug(query.message.chat_id) 52 | 53 | 54 | # Add GMAIL Account 55 | 56 | def add_gmail_account(bot, update): 57 | query = update.callback_query 58 | 59 | db = DBC() 60 | 61 | try: 62 | db.search_user(str(query.message.chat_id)) 63 | except: 64 | db.insert_user(str(query.message.chat_id), []) 65 | 66 | query.message.reply_text('Type your email address:') 67 | logging.debug(query.message.chat_id) 68 | 69 | return ACCOUNT 70 | 71 | 72 | # Add OUTLOOK Account (Not Available Yet) 73 | 74 | def add_outlook_account(bot, update): 75 | query = update.callback_query 76 | query.message.reply_text('Option not available yet') 77 | 78 | 79 | # Add OTHER Account (Not Available Yet) 80 | 81 | def add_other_account(bot, update): 82 | query = update.callback_query 83 | query.message.reply_text('Option not available yet') 84 | 85 | 86 | # Add Account process 87 | 88 | def add_gmail_username_account(bot, update, user_data): 89 | db = DBC() 90 | email_server = db.search_email_server('GMAIL', 'IMAP') 91 | account = Account('GMAIL', None, None, email_server.host, email_server.port, email_server.protocol, None) 92 | account.username = update.message.text 93 | user_data['account'] = account 94 | 95 | update.message.reply_text('Type your password:') 96 | 97 | return PASSWORD 98 | 99 | 100 | def add_password_account(bot, update, user_data): 101 | account = user_data['account'] 102 | account.password = update.message.text 103 | user_data['account'] = account 104 | 105 | update.message.reply_text('Type your desired refresh_time in seconds (type 0 to set Default):') 106 | 107 | return REFRESH_TIME 108 | 109 | 110 | def add_refresh_time_account(bot, update, user_data): 111 | db = DBC() 112 | user = db.search_user(str(update.message.chat_id)) 113 | account = user_data['account'] 114 | if int(update.message.text) != 0: 115 | account.refresh_time = int(update.message.text) 116 | db.add_account_to_user(user, account) 117 | 118 | update.message.reply_text('Great! Your account has been saved.') 119 | 120 | return ConversationHandler.END 121 | 122 | 123 | # Modify Account process 124 | 125 | def modify_account(bot, update): 126 | query = update.callback_query 127 | 128 | keyboard = [[InlineKeyboardButton("Modify Password", callback_data='/account/modify/password')], 129 | [InlineKeyboardButton("Modify Refresh Time", callback_data='/account/modify/refresh_time')]] 130 | 131 | reply_markup = InlineKeyboardMarkup(keyboard) 132 | 133 | query.message.reply_text('What do you want to modify on your Accounts?', reply_markup=reply_markup) 134 | logging.debug(query.message.chat_id) 135 | 136 | # Modify Password process 137 | 138 | ACCOUNT, PASSWORD = range(2) 139 | 140 | 141 | def modify_password(bot, update): 142 | query = update.callback_query 143 | 144 | query.message.reply_text('Okay. Type the email address of the account you want to modify your password:') 145 | 146 | return ACCOUNT 147 | 148 | 149 | def modify_account_password(bot, update, user_data): 150 | user_data['username'] = update.message.text 151 | 152 | update.message.reply_text('Now type your new password:') 153 | 154 | return PASSWORD 155 | 156 | 157 | def modify_password_password(bot, update, user_data): 158 | db = DBC() 159 | user = db.search_user(str(update.message.chat_id)) 160 | account = db.get_account_of_user(user, user_data['username']) 161 | account.password = update.message.text 162 | db.update_account_of_user(user, account) 163 | 164 | update.message.reply_text('Password modified successfully!') 165 | 166 | return ConversationHandler.END 167 | 168 | 169 | # Modify Refresh_Time process 170 | 171 | ACCOUNT, REFRESH_TIME = range(2) 172 | 173 | 174 | def modify_refresh_time(bot, update): 175 | query = update.callback_query 176 | 177 | query.message.reply_text('Okay. Type the email address of the account you want to modify your refresh_time:') 178 | 179 | return ACCOUNT 180 | 181 | 182 | def modify_account_refresh_time(bot, update, user_data): 183 | user_data['username'] = update.message.text 184 | 185 | update.message.reply_text('Now type your new refresh_time:') 186 | 187 | return REFRESH_TIME 188 | 189 | 190 | def modify_refresh_time_refresh_time(bot, update, user_data): 191 | db = DBC() 192 | user = db.search_user(str(update.message.chat_id)) 193 | account = db.get_account_of_user(user, user_data['username']) 194 | account.refresh_time = int(update.message.text) 195 | db.update_account_of_user(user, account) 196 | 197 | update.message.reply_text('Refresh Time modified successfully!') 198 | 199 | return ConversationHandler.END 200 | 201 | # Remove Account process 202 | 203 | ACCOUNT = range(1) 204 | 205 | 206 | def remove_account(bot, update): 207 | query = update.callback_query 208 | 209 | query.message.reply_text('Type the email address of the account you want to remove:') 210 | 211 | return ACCOUNT 212 | 213 | 214 | def remove_account_account(bot, update): 215 | db = DBC() 216 | user = db.search_user(str(update.message.chat_id)) 217 | account = db.get_account_of_user(user, update.message.text) 218 | db.remove_account_of_user(user, account) 219 | 220 | update.message.reply_text('Account removed successfully!') 221 | 222 | return ConversationHandler.END 223 | 224 | # Cancel Option 225 | 226 | def cancel(bot, update): 227 | user = update.message.from_user 228 | logging.info("User %s canceled the conversation." % user.first_name) 229 | update.message.reply_text('Operation cancelled, you have stopped the Account process.') 230 | 231 | return ConversationHandler.END 232 | -------------------------------------------------------------------------------- /commands/email.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ChatAction 18 | import logging 19 | from services.email import get_email_server 20 | from utils.telegram import emojis, load_main_view 21 | 22 | folders_by_page = 8 23 | 24 | 25 | def view_detailed_email(bot, update): 26 | query = update.callback_query 27 | try: 28 | data = filter_callback_data(update, "/email/view", 3) 29 | user_email = data[0] 30 | msg_uid = bytes(data[1], 'utf-8') 31 | folder = data[2] 32 | 33 | msg = get_email_server(user_email).get_email_by_uid(folder, msg_uid) 34 | message = msg.get_body() 35 | 36 | response, reply_markup = load_main_view(msg, back="details") 37 | 38 | if message != None and len(message) > 4000: 39 | message = message[:4000] + " ..." 40 | 41 | bot.edit_message_text(text=message, 42 | chat_id=query.message.chat_id, 43 | message_id=query.message.message_id, 44 | reply_markup=reply_markup) 45 | query.answer() 46 | except: 47 | logging.error("view_detailed_email error") 48 | query.answer(text="view_detailed_email error") 49 | 50 | 51 | def view_email(bot, update): 52 | query = update.callback_query 53 | 54 | data = filter_callback_data(update, "/email/view", 3) 55 | email = data[0] 56 | msg_uid = bytes(data[1], 'utf-8') 57 | folder = data[2] 58 | 59 | response, reply_markup = load_main_view(get_email_server(email).get_email_by_uid(folder, msg_uid)) 60 | 61 | bot.edit_message_text(parse_mode="Markdown", 62 | text=response, 63 | chat_id=query.message.chat_id, 64 | message_id=query.message.message_id, 65 | reply_markup=reply_markup) 66 | query.answer() 67 | 68 | 69 | def mark_read_email(bot, update): 70 | query = update.callback_query 71 | try: 72 | data = filter_callback_data(update, "/email/mark_read", 3) 73 | user_email = data[0] 74 | msg_uid = bytes(data[1], 'utf-8') 75 | folder = data[2] 76 | 77 | get_email_server(user_email).mark_as_read(folder, msg_uid, True) 78 | 79 | response, reply_markup = load_main_view(get_email_server(user_email).get_email_by_uid(folder, msg_uid)) 80 | 81 | bot.edit_message_text(parse_mode="Markdown", 82 | text=response + "--", 83 | chat_id=query.message.chat_id, 84 | message_id=query.message.message_id, 85 | reply_markup=reply_markup) 86 | query.answer() 87 | except: 88 | logging.error("mark_read_email error") 89 | query.answer(text="mark_read_email error") 90 | 91 | 92 | def mark_unread_email(bot, update): 93 | query = update.callback_query 94 | try: 95 | data = filter_callback_data(update, "/email/mark_unread", 3) 96 | user_email = data[0] 97 | msg_uid = bytes(data[1], 'utf-8') 98 | folder = data[2] 99 | get_email_server(user_email).mark_as_read(folder, msg_uid, False) 100 | 101 | response, reply_markup = load_main_view(get_email_server(user_email).get_email_by_uid(folder, msg_uid)) 102 | bot.edit_message_text(parse_mode="Markdown", 103 | text=response + "++", 104 | chat_id=query.message.chat_id, 105 | message_id=query.message.message_id, 106 | reply_markup=reply_markup) 107 | query.answer() 108 | except: 109 | logging.error("mark_unread_email error") 110 | query.answer(text="mark_unread_email error") 111 | 112 | 113 | def archive_email(bot, update): 114 | query = update.callback_query 115 | try: 116 | data = filter_callback_data(update, "/email/archive", 3) 117 | user_email = data[0] 118 | msg_uid = bytes(data[1], 'utf-8') 119 | folder = data[2] 120 | get_email_server(user_email).delete_from_folder(msg_uid, folder) 121 | 122 | previous_response = query.message.text_markdown 123 | bot.edit_message_text(parse_mode="Markdown", 124 | text=previous_response+"\n\n"+emojis["archive"]+"Archived! "+emojis["archive"], 125 | chat_id=query.message.chat_id, 126 | message_id=query.message.message_id) 127 | query.answer() 128 | except Exception as e: 129 | logging.error(e) 130 | logging.error("archive_email error") 131 | query.answer(text="archive_email error") 132 | 133 | 134 | def label_list_email(bot, update): 135 | query = update.callback_query 136 | try: 137 | data = filter_callback_data(update, "/email/label_l", 4) 138 | user_email = data[1] 139 | msg_uid = bytes(data[2], 'utf-8') 140 | page = data[0] 141 | folder = data[3] 142 | # folders = get_email_server(user_email).get_folders() 143 | 144 | common_sufix = '/' + user_email + '/' + msg_uid.decode() + '/' + folder 145 | 146 | header = [] 147 | 148 | header.append(InlineKeyboardButton(emojis["back"], callback_data='/email/back' + common_sufix)) 149 | print(int(page)) 150 | 151 | # if int(page) > 0: # Need previous page button 152 | # header.append(InlineKeyboardButton(emojis["previous_page"], callback_data='/email/label_l/' + 153 | # str(int(page)-1) + common_sufix)) 154 | header.append(InlineKeyboardButton(emojis["archive"], callback_data='/email/archive' + common_sufix)) 155 | header.append(InlineKeyboardButton(emojis["delete"], callback_data='/email/delete'+common_sufix)) 156 | # header.append(InlineKeyboardButton(emojis["link"], callback_data='/email/link' + common_sufix)) 157 | 158 | # if (len(folders) - (int(page) + 1) * folders_by_page) > 0: # Need next page button 159 | # header.append(InlineKeyboardButton(emojis["next_page"], callback_data='/email/label_l/' + 160 | # str(int(page)+1) + common_sufix)) 161 | body = [header] 162 | # for a in range(0, int(folders_by_page/2)): 163 | # n = a * 2 + (int(page) * folders_by_page) 164 | # body.append([ 165 | # InlineKeyboardButton(folders[n].name, callback_data='/email/label' + common_sufix), 166 | # InlineKeyboardButton(folders[n+1].name, callback_data='/email/label' + common_sufix), 167 | # ]) 168 | 169 | response, reply_markup = load_main_view(get_email_server(user_email).get_email_by_uid(folder, msg_uid)) 170 | bot.edit_message_text(parse_mode="Markdown", 171 | text=response + "+-", 172 | chat_id=query.message.chat_id, 173 | message_id=query.message.message_id, 174 | reply_markup=InlineKeyboardMarkup(body)) 175 | query.answer() 176 | except Exception as e: 177 | logging.error(e) 178 | logging.error("label_list_email error") 179 | query.answer(text="label_list_email error") 180 | 181 | 182 | def delete_email(bot, update): 183 | query = update.callback_query 184 | try: 185 | data = filter_callback_data(update, "/email/delete", 3) 186 | user_email = data[0] 187 | msg_uid = bytes(data[1], 'utf-8') 188 | folder = data[2] 189 | 190 | get_email_server(user_email).add_to_folder(msg_uid, 'inbox', '[Gmail]/Trash') 191 | get_email_server(user_email).delete_from_folder(msg_uid, 'Inbox') 192 | 193 | previous_response = query.message.text_markdown 194 | 195 | bot.edit_message_text(parse_mode="Markdown", 196 | text=previous_response+"\n\n"+emojis["delete"]+"Deleted! "+emojis["delete"], 197 | chat_id=query.message.chat_id, 198 | message_id=query.message.message_id) 199 | query.answer() 200 | except Exception as e: 201 | logging.error(e) 202 | logging.error("delete_email error") 203 | query.answer(text="delete_email error") 204 | 205 | 206 | 207 | def help_email(bot, update): 208 | text = emojis["back"] + " previous content\n" 209 | text += emojis["help"] + " show this menu\n" 210 | # text += emojis["link"] + " link to web email\n" 211 | text += emojis["details"] + " show additionals details\n" 212 | text += emojis["archive"] + " archive the message\n" 213 | # text += emojis["reply"] + " reply to the message\n" 214 | # text += emojis["remember"] + " remember in the future\n" 215 | text += emojis["label"] + " manage labels\n" 216 | text += emojis["mark_as_unread"] + "/" + emojis["mark_as_read"] + " mark as unread/read\n" 217 | bot.send_message(chat_id=update.effective_chat.id, parse_mode="Markdown", 218 | text=text) 219 | 220 | 221 | # Prefix without last / 222 | def filter_callback_data(update, prefix, fields=1, separator='/'): 223 | data = update.callback_query.data[len(prefix)+1:] 224 | 225 | return data.split(separator, fields-1) 226 | -------------------------------------------------------------------------------- /commands/generic.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 18 | import logging 19 | 20 | 21 | def start(bot, update): 22 | keyboard = [[InlineKeyboardButton("Option 1", callback_data='/start/1'), 23 | InlineKeyboardButton("Option 2", callback_data='/notStart/2')], 24 | 25 | [InlineKeyboardButton("Accounts", callback_data='/account/options')]] 26 | 27 | reply_markup = InlineKeyboardMarkup(keyboard) 28 | 29 | update.message.reply_text('Please choose:', reply_markup=reply_markup) 30 | logging.debug(update.message.chat_id) 31 | 32 | 33 | def help(bot, update): 34 | update.message.reply_text("With this bot you can say goodbye to your ugly email's clients. Feel free of use your " 35 | "favorites emails account now in Telegram too!" 36 | "\n\nUse /start to start to use this bot!!" 37 | "\n\nYou can see the help about Email's buttons at the ❓ option." 38 | "\n\nFeatures:" 39 | "\n ✔ Auto check email account and notify news." 40 | "\n ✔️ Friendly interface." 41 | "\n ✔️ Multiple email accounts." 42 | "\n ✔️ Compatible with IMAP protocol. (More in the future)." 43 | "\n ✔️ Read email on Telegram, mark as read/unread, archive/delete and much more." 44 | "\n\nYou can visit or contribute the project at: https://github.com/ManuelLR/Notmail_Bot") 45 | 46 | 47 | def error(bot, update, error): 48 | logging.warning('Update "%s" caused error "%s"' % (update, error)) 49 | 50 | 51 | def button(bot, update): 52 | query = update.callback_query 53 | 54 | bot.edit_message_text(text="Selected option: %s" % query.data, 55 | chat_id=query.message.chat_id, 56 | message_id=query.message.message_id) 57 | 58 | 59 | -------------------------------------------------------------------------------- /commands/login.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ManuelLR/Notmail_Bot/faf4a6fd3ed5f1809934e615fcb75bd8174b2bfc/commands/login.py -------------------------------------------------------------------------------- /config/loadConfig.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | import os, tempfile, errno, sys 18 | import logging 19 | from configparser import ConfigParser 20 | 21 | 22 | # Solo cargará las variables del archivo de configuración si se especifica el archivo al lanzar el programa 23 | 24 | global_config = None 25 | 26 | 27 | class Config: 28 | def __init_empty_vars(self): 29 | self.telegram_token = None 30 | self.telegram_admin_user_id = None 31 | self.telegram_admin_username = None 32 | self.default_refresh_inbox = None 33 | self.log_path = None 34 | self.db_path = None 35 | self.log_level = None 36 | 37 | def __init__(self): 38 | self.__init_empty_vars() 39 | # ======== Telegram 40 | self.__set_telegram_token(os.getenv('TELEGRAM_TOKEN', "")) 41 | self.__set_telegram_admin_user_id(os.getenv('TELEGRAM_ADMIN_USER_ID', "")) 42 | self.__set_telegram_admin_username(os.getenv('TELEGRAM_ADMIN_USERNAME', "")) 43 | 44 | # ======== Database 45 | self.__set_db_path(os.getenv('TMAIL_DB_PATH', os.path.join("my-config", "notmail_bot-db.json"))) 46 | 47 | # ======== Email 48 | self.__set_default_refresh_inbox(os.getenv('TMAIL_DEFAULT_REFRESH_TIME', 3 * 60)) # 3 minutos 49 | 50 | # ======== Log 51 | self.__set_log_level(os.getenv('TMAIL_LOG_LEVEL', "INFO")) 52 | self.__set_log_path(os.getenv('TMAIL_LOG_PATH', None)) 53 | 54 | def load_config_file(self, path): 55 | if not is_path_exists_or_creatable_portable(path): 56 | raise AssertionError 57 | config = ConfigParser() 58 | config.read(path) 59 | 60 | self.__set_telegram_token(self.__lod(config, 'Telegram', 'TOKEN', self.telegram_token)) 61 | self.__set_telegram_admin_username(self.__lod(config, 'Telegram', 'ADMIN_USERNAME', self.telegram_admin_username)) 62 | self.__set_telegram_admin_user_id(self.__lod(config, 'Telegram', 'ADMIN_USER_ID', self.telegram_admin_user_id)) 63 | 64 | self.__set_db_path(self.__lod(config, 'Database', 'PATH', self.db_path)) 65 | 66 | self.__set_default_refresh_inbox(self.__lod(config, 'Email', 'DEFAULT_REFRESH_TIME', self.default_refresh_inbox)) 67 | 68 | self.__set_log_level(self.__lod(config, 'Log', 'LOG_LEVEL', self.log_level)) 69 | self.__set_log_path(self.__lod(config, 'Log', 'LOG_PATH', self.log_path)) 70 | 71 | def load_config_variables(self, token, admin_user_id, admin_username, db_path, refresh_inbox, log_level, log_path): 72 | self.__set_telegram_token(self.__lov(token, self.telegram_token)) 73 | self.__set_telegram_admin_username(self.__lov(admin_user_id, self.telegram_admin_username)) 74 | self.__set_telegram_admin_user_id(self.__lov(admin_username, self.telegram_admin_user_id)) 75 | 76 | self.__set_db_path(self.__lov(db_path, self.db_path)) 77 | 78 | self.__set_default_refresh_inbox(self.__lov(refresh_inbox, self.default_refresh_inbox)) 79 | 80 | self.__set_log_level(self.__lov(log_level, self.log_level)) 81 | self.__set_log_path(self.__lov(log_path, self.log_path)) 82 | 83 | @staticmethod 84 | def __lod(config, section, key, default_value=None): 85 | if config.has_option(section, key): 86 | return config[section][key] 87 | else: 88 | return default_value 89 | 90 | @staticmethod 91 | def __lov(var, default_value=None): 92 | if var: 93 | return var 94 | else: 95 | return default_value 96 | 97 | def __set_telegram_token(self, inp): 98 | if not isinstance(inp, str): 99 | raise AssertionError 100 | self.telegram_token = inp 101 | 102 | def __set_telegram_admin_user_id(self, inp): 103 | if not isinstance(inp, str): 104 | raise AssertionError 105 | self.telegram_admin_user_id = inp 106 | 107 | def __set_telegram_admin_username(self, inp): 108 | if not isinstance(inp, str): 109 | raise AssertionError 110 | self.telegram_admin_username = inp 111 | 112 | def __set_default_refresh_inbox(self, inp): 113 | if isinstance(inp, str): 114 | inp = int(inp) 115 | if not isinstance(inp, int): 116 | raise AssertionError 117 | self.default_refresh_inbox = inp 118 | 119 | def __set_log_level(self, inp): 120 | level = logging. _nameToLevel.get(inp) 121 | if level is None: 122 | if logging._levelToName.get(inp) is None: 123 | raise AssertionError 124 | else: 125 | self.log_level = inp 126 | else: 127 | self.log_level = level 128 | 129 | def __set_log_path(self, inp): 130 | if not is_path_exists_or_creatable_portable(inp): 131 | return 132 | self.log_path = inp 133 | 134 | def __set_db_path(self, inp): 135 | if not is_path_exists_or_creatable_portable(inp): 136 | raise AssertionError 137 | self.db_path = inp 138 | 139 | 140 | def get_config(): 141 | return global_config 142 | 143 | 144 | def set_config(conf): 145 | global global_config 146 | global_config = conf 147 | 148 | # ------------ https://stackoverflow.com/a/34102855 149 | 150 | # Sadly, Python fails to provide the following magic number for us. 151 | ERROR_INVALID_NAME = 123 152 | 153 | ''' 154 | Windows-specific error code indicating an invalid pathname. 155 | 156 | See Also 157 | ---------- 158 | https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382%28v=vs.85%29.aspx 159 | Official listing of all such codes. 160 | ''' 161 | def is_pathname_valid(pathname: str) -> bool: 162 | ''' 163 | `True` if the passed pathname is a valid pathname for the current OS; 164 | `False` otherwise. 165 | ''' 166 | # If this pathname is either not a string or is but is empty, this pathname 167 | # is invalid. 168 | try: 169 | if not isinstance(pathname, str) or not pathname: 170 | return False 171 | 172 | # Strip this pathname's Windows-specific drive specifier (e.g., `C:\`) 173 | # if any. Since Windows prohibits path components from containing `:` 174 | # characters, failing to strip this `:`-suffixed prefix would 175 | # erroneously invalidate all valid absolute Windows pathnames. 176 | _, pathname = os.path.splitdrive(pathname) 177 | 178 | # Directory guaranteed to exist. If the current OS is Windows, this is 179 | # the drive to which Windows was installed (e.g., the "%HOMEDRIVE%" 180 | # environment variable); else, the typical root directory. 181 | root_dirname = os.environ.get('HOMEDRIVE', 'C:') \ 182 | if sys.platform == 'win32' else os.path.sep 183 | assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law 184 | 185 | # Append a path separator to this directory if needed. 186 | root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep 187 | 188 | # Test whether each path component split from this pathname is valid or 189 | # not, ignoring non-existent and non-readable path components. 190 | for pathname_part in pathname.split(os.path.sep): 191 | try: 192 | os.lstat(root_dirname + pathname_part) 193 | # If an OS-specific exception is raised, its error code 194 | # indicates whether this pathname is valid or not. Unless this 195 | # is the case, this exception implies an ignorable kernel or 196 | # filesystem complaint (e.g., path not found or inaccessible). 197 | # 198 | # Only the following exceptions indicate invalid pathnames: 199 | # 200 | # * Instances of the Windows-specific "WindowsError" class 201 | # defining the "winerror" attribute whose value is 202 | # "ERROR_INVALID_NAME". Under Windows, "winerror" is more 203 | # fine-grained and hence useful than the generic "errno" 204 | # attribute. When a too-long pathname is passed, for example, 205 | # "errno" is "ENOENT" (i.e., no such file or directory) rather 206 | # than "ENAMETOOLONG" (i.e., file name too long). 207 | # * Instances of the cross-platform "OSError" class defining the 208 | # generic "errno" attribute whose value is either: 209 | # * Under most POSIX-compatible OSes, "ENAMETOOLONG". 210 | # * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE". 211 | except OSError as exc: 212 | if hasattr(exc, 'winerror'): 213 | if exc.winerror == ERROR_INVALID_NAME: 214 | return False 215 | elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}: 216 | return False 217 | # If a "TypeError" exception was raised, it almost certainly has the 218 | # error message "embedded NUL character" indicating an invalid pathname. 219 | except TypeError as exc: 220 | return False 221 | # If no exception was raised, all path components and hence this 222 | # pathname itself are valid. (Praise be to the curmudgeonly python.) 223 | else: 224 | return True 225 | # If any other exception was raised, this is an unrelated fatal issue 226 | # (e.g., a bug). Permit this exception to unwind the call stack. 227 | # 228 | # Did we mention this should be shipped with Python already? 229 | 230 | 231 | def is_path_creatable(pathname: str) -> bool: 232 | ''' 233 | `True` if the current user has sufficient permissions to create the passed 234 | pathname; `False` otherwise. 235 | ''' 236 | # Parent directory of the passed path. If empty, we substitute the current 237 | # working directory (CWD) instead. 238 | dirname = os.path.dirname(pathname) or os.getcwd() 239 | return os.access(dirname, os.W_OK) 240 | 241 | 242 | def is_path_exists_or_creatable(pathname: str) -> bool: 243 | ''' 244 | `True` if the passed pathname is a valid pathname for the current OS _and_ 245 | either currently exists or is hypothetically creatable; `False` otherwise. 246 | 247 | This function is guaranteed to _never_ raise exceptions. 248 | ''' 249 | try: 250 | # To prevent "os" module calls from raising undesirable exceptions on 251 | # invalid pathnames, is_pathname_valid() is explicitly called first. 252 | return is_pathname_valid(pathname) and ( 253 | os.path.exists(pathname) or is_path_creatable(pathname)) 254 | # Report failure on non-fatal filesystem complaints (e.g., connection 255 | # timeouts, permissions issues) implying this path to be inaccessible. All 256 | # other exceptions are unrelated fatal issues and should not be caught here. 257 | except OSError: 258 | return False 259 | 260 | 261 | def is_path_sibling_creatable(pathname: str) -> bool: 262 | ''' 263 | `True` if the current user has sufficient permissions to create **siblings** 264 | (i.e., arbitrary files in the parent directory) of the passed pathname; 265 | `False` otherwise. 266 | ''' 267 | # Parent directory of the passed path. If empty, we substitute the current 268 | # working directory (CWD) instead. 269 | dirname = os.path.dirname(pathname) or os.getcwd() 270 | 271 | try: 272 | # For safety, explicitly close and hence delete this temporary file 273 | # immediately after creating it in the passed path's parent directory. 274 | with tempfile.TemporaryFile(dir=dirname): pass 275 | return True 276 | # While the exact type of exception raised by the above function depends on 277 | # the current version of the Python interpreter, all such types subclass the 278 | # following exception superclass. 279 | except EnvironmentError: 280 | return False 281 | 282 | 283 | def is_path_exists_or_creatable_portable(pathname: str) -> bool: 284 | ''' 285 | `True` if the passed pathname is a valid pathname on the current OS _and_ 286 | either currently exists or is hypothetically creatable in a cross-platform 287 | manner optimized for POSIX-unfriendly filesystems; `False` otherwise. 288 | 289 | This function is guaranteed to _never_ raise exceptions. 290 | ''' 291 | try: 292 | # To prevent "os" module calls from raising undesirable exceptions on 293 | # invalid pathnames, is_pathname_valid() is explicitly called first. 294 | return is_pathname_valid(pathname) and ( 295 | os.path.exists(pathname) or is_path_sibling_creatable(pathname)) 296 | # Report failure on non-fatal filesystem complaints (e.g., connection 297 | # timeouts, permissions issues) implying this path to be inaccessible. All 298 | # other exceptions are unrelated fatal issues and should not be caught here. 299 | except OSError: 300 | return False 301 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.2' 2 | 3 | services: 4 | bot: 5 | build: . 6 | restart: always 7 | volumes: 8 | - notmail-config:/usr/src/bot/my-config 9 | env_file: 10 | - .env 11 | 12 | volumes: 13 | notmail-config: 14 | -------------------------------------------------------------------------------- /img/notmail_bot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ManuelLR/Notmail_Bot/faf4a6fd3ed5f1809934e615fcb75bd8174b2bfc/img/notmail_bot.png -------------------------------------------------------------------------------- /img/notmail_bot.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 23 | 25 | 32 | 36 | 40 | 41 | 49 | 53 | 57 | 58 | 66 | 70 | 74 | 75 | 85 | 86 | 113 | 115 | 116 | 118 | image/svg+xml 119 | 121 | 122 | 123 | 124 | 125 | 132 | 138 | 139 | 146 | 159 | 168 | 176 | 181 | 186 | 191 | 196 | 201 | 206 | 211 | 216 | 221 | 225 | 230 | 235 | 236 | 242 | 248 | 254 | 255 | 256 | 257 | -------------------------------------------------------------------------------- /img/notmail_bot_license.txt: -------------------------------------------------------------------------------- 1 | Free Art License 1.3 2 | 3 | [ Copyleft Attitude ] 4 | 5 | Free Art License 1.3 (FAL 1.3) 6 | 7 | Preamble 8 | 9 | The Free Art License grants the right to freely copy, distribute, and transform creative works without infringing the author’s rights. 10 | 11 | The Free Art License recognizes and protects these rights. Their implementation has been reformulated in order to allow everyone to use creations of the human mind in a creative manner, regardless of their types and ways of expression. 12 | 13 | While the public’s access to creations of the human mind usually is restricted by the implementation of copyright law, it is favoured by the Free Art License. This license intends to allow the use of a work’s resources; to establish new conditions for creating in order to increase creation opportunities. The Free Art License grants the right to use a work, and acknowledges the right holder’s and the user’s rights and responsibility. 14 | 15 | The invention and development of digital technologies, Internet and Free Software have changed creation methods: creations of the human mind can obviously be distributed, exchanged, and transformed. They allow to produce common works to which everyone can contribute to the benefit of all. 16 | 17 | The main rationale for this Free Art License is to promote and protect these creations of the human mind according to the principles of copyleft: freedom to use, copy, distribute, transform, and prohibition of exclusive appropriation. 18 | 19 | Definitions 20 | 21 | « work » either means the initial work, the subsequent works or the common work as defined hereafter: 22 | 23 | « common work » means a work composed of the initial work and all subsequent contributions to it (originals and copies). The initial author is the one who, by choosing this license, defines the conditions under which contributions are made. 24 | 25 | « Initial work » means the work created by the initiator of the common work (as defined above), the copies of which can be modified by whoever wants to 26 | 27 | « Subsequent works » means the contributions made by authors who participate in the evolution of the common work by exercising the rights to reproduce, distribute, and modify that are granted by the license. 28 | 29 | « Originals » (sources or resources of the work) means all copies of either the initial work or any subsequent work mentioning a date and used by their author(s) as references for any subsequent updates, interpretations, copies or reproductions. 30 | 31 | « Copy » means any reproduction of an original as defined by this license. 32 | 33 | 1. OBJECT 34 | The aim of this license is to define the conditions under which one can use this work freely. 35 | 36 | 2. SCOPE 37 | This work is subject to copyright law. Through this license its author specifies the extent to which you can copy, distribute, and modify it. 38 | 39 | 2.1 FREEDOM TO COPY (OR TO MAKE REPRODUCTIONS) 40 | You have the right to copy this work for yourself, your friends or any other person, whatever the technique used. 41 | 42 | 2.2 FREEDOM TO DISTRIBUTE, TO PERFORM IN PUBLIC 43 | You have the right to distribute copies of this work; whether modified or not, whatever the medium and the place, with or without any charge, provided that you: 44 | attach this license without any modification to the copies of this work or indicate precisely where the license can be found, 45 | specify to the recipient the names of the author(s) of the originals, including yours if you have modified the work, 46 | specify to the recipient where to access the originals (either initial or subsequent). 47 | The authors of the originals may, if they wish to, give you the right to distribute the originals under the same conditions as the copies. 48 | 49 | 2.3 FREEDOM TO MODIFY 50 | You have the right to modify copies of the originals (whether initial or subsequent) provided you comply with the following conditions: 51 | all conditions in article 2.2 above, if you distribute modified copies; 52 | indicate that the work has been modified and, if it is possible, what kind of modifications have been made; 53 | distribute the subsequent work under the same license or any compatible license. 54 | The author(s) of the original work may give you the right to modify it under the same conditions as the copies. 55 | 56 | 3. RELATED RIGHTS 57 | Activities giving rise to author’s rights and related rights shall not challenge the rights granted by this license. 58 | For example, this is the reason why performances must be subject to the same license or a compatible license. Similarly, integrating the work in a database, a compilation or an anthology shall not prevent anyone from using the work under the same conditions as those defined in this license. 59 | 60 | 4. INCORPORATION OF THE WORK 61 | Incorporating this work into a larger work that is not subject to the Free Art License shall not challenge the rights granted by this license. 62 | If the work can no longer be accessed apart from the larger work in which it is incorporated, then incorporation shall only be allowed under the condition that the larger work is subject either to the Free Art License or a compatible license. 63 | 64 | 5. COMPATIBILITY 65 | A license is compatible with the Free Art License provided: 66 | it gives the right to copy, distribute, and modify copies of the work including for commercial purposes and without any other restrictions than those required by the respect of the other compatibility criteria; 67 | it ensures proper attribution of the work to its authors and access to previous versions of the work when possible; 68 | it recognizes the Free Art License as compatible (reciprocity); 69 | it requires that changes made to the work be subject to the same license or to a license which also meets these compatibility criteria. 70 | 71 | 6. YOUR INTELLECTUAL RIGHTS 72 | This license does not aim at denying your author’s rights in your contribution or any related right. By choosing to contribute to the development of this common work, you only agree to grant others the same rights with regard to your contribution as those you were granted by this license. Conferring these rights does not mean you have to give up your intellectual rights. 73 | 74 | 7. YOUR RESPONSIBILITIES 75 | The freedom to use the work as defined by the Free Art License (right to copy, distribute, modify) implies that everyone is responsible for their own actions. 76 | 77 | 8. DURATION OF THE LICENSE 78 | This license takes effect as of your acceptance of its terms. The act of copying, distributing, or modifying the work constitutes a tacit agreement. This license will remain in effect for as long as the copyright which is attached to the work. If you do not respect the terms of this license, you automatically lose the rights that it confers. 79 | If the legal status or legislation to which you are subject makes it impossible for you to respect the terms of this license, you may not make use of the rights which it confers. 80 | 81 | 9. VARIOUS VERSIONS OF THE LICENSE 82 | This license may undergo periodic modifications to incorporate improvements by its authors (instigators of the « Copyleft Attitude » movement) by way of new, numbered versions. 83 | You will always have the choice of accepting the terms contained in the version under which the copy of the work was distributed to you, or alternatively, to use the provisions of one of the subsequent versions. 84 | 85 | 10. SUB-LICENSING 86 | Sub-licenses are not authorized by this license. Any person wishing to make use of the rights that it confers will be directly bound to the authors of the common work. 87 | 88 | 11. LEGAL FRAMEWORK 89 | This license is written with respect to both French law and the Berne Convention for the Protection of Literary and Artistic Works. 90 | 91 | USER GUIDE 92 | 93 | – How to use the Free Art License? 94 | To benefit from the Free Art License, you only need to mention the following elements on your work: 95 | [Name of the author, title, date of the work. When applicable, names of authors of the common work and, if possible, where to find the originals]. 96 | Copyleft: This is a free work, you can copy, distribute, and modify it under the terms of the Free Art License http://artlibre.org/licence/lal/en/ 97 | 98 | – Why to use the Free Art License? 99 | 1.To give the greatest number of people access to your work. 100 | 2.To allow it to be distributed freely. 101 | 3.To allow it to evolve by allowing its copy, distribution, and transformation by others. 102 | 4.So that you benefit from the resources of a work when it is under the Free Art License: to be able to copy, distribute or transform it freely. 103 | 5.But also, because the Free Art License offers a legal framework to disallow any misappropriation. It is forbidden to take hold of your work and bypass the creative process for one’s exclusive possession. 104 | 105 | – When to use the Free Art License? 106 | Any time you want to benefit and make others benefit from the right to copy, distribute and transform creative works without any exclusive appropriation, you should use the Free Art License. You can for example use it for scientific, artistic or educational projects. 107 | 108 | – What kinds of works can be subject to the Free Art License? 109 | The Free Art License can be applied to digital as well as physical works. 110 | You can choose to apply the Free Art License on any text, picture, sound, gesture, or whatever sort of stuff on which you have sufficient author’s rights. 111 | 112 | – Historical background of this license: 113 | It is the result of observing, using and creating digital technologies, free software, the Internet and art. It arose from the « Copyleft Attitude » meetings which took place in Paris in 2000. For the first time, these meetings brought together members of the Free Software community, artists, and members of the art world. The goal was to adapt the principles of Copyleft and free software to all sorts of creations. http://www.artlibre.org 114 | 115 | Copyleft Attitude, 2007. 116 | You can make reproductions and distribute this license verbatim (without any changes). 117 | 118 | Translation : Jonathan Clarke, Benjamin Jean, Griselda Jung, Fanny Mourguet, Antoine Pitrou. 119 | Thanks to framalang.org 120 | -------------------------------------------------------------------------------- /my-config/.empty: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /my-config/config_example.ini: -------------------------------------------------------------------------------- 1 | [Telegram] 2 | ADMIN_USER_ID=12345678 3 | ADMIN_USERNAME=my_userName 4 | TOKEN=xxxxxxx:XXXXXXXXXXXXXXXXXXXX 5 | 6 | [Database] 7 | PATH=my-config/Notmail-bot.json 8 | 9 | [Email] 10 | DEFAULT_REFRESH_TIME=180 11 | 12 | [Log] 13 | LOG_LEVEL=INFO 14 | LOG_PATH=my-config/Notmail-bot.log 15 | -------------------------------------------------------------------------------- /notmail_bot.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | import logging 18 | from telegram.ext import Updater 19 | import click # http://click.pocoo.org/6/ 20 | from services.email import init_email_service 21 | from utils.scheduler import init_scheduler 22 | from commands import load_dispatcher 23 | from services import set_bot 24 | from config.loadConfig import Config, get_config, set_config 25 | from repository.repository import DBC, set_dbc 26 | 27 | @click.command() 28 | @click.option('--config_path', default=None, help='Path to config file. It overwrite all env variables') 29 | @click.option('--token', help='The bot token. Please talk with @BotFather') 30 | @click.option('--admin_user_id', help='The bot token. Please talk with @BotFather') 31 | @click.option('--admin_username', help='The bot token. Please talk with @BotFather') 32 | @click.option('--db_path', help='Path to db (could be empty)') 33 | @click.option('--refresh_inbox', help='The time between mail checks') 34 | @click.option('--log_level', help='Level to log. [INFO, DEBUG]') 35 | @click.option('--log_path', help='The bot token. Please talk with @BotFather') 36 | def init(config_path, token, admin_user_id, admin_username, db_path, refresh_inbox, log_level, log_path): 37 | 38 | set_config(Config()) 39 | if config_path: 40 | get_config().load_config_file(config_path) 41 | get_config().load_config_variables(token, admin_user_id, admin_username, db_path, refresh_inbox, log_level, log_path) 42 | 43 | # ================== Initializer ================== 44 | set_dbc(DBC(path=get_config().db_path)) 45 | init_scheduler() 46 | 47 | # ============== LOGs ============ 48 | log_formatter = logging.Formatter(fmt='[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s', 49 | datefmt='%d-%m-%y %H:%M:%S') 50 | 51 | logger = logging.getLogger() 52 | 53 | if get_config().log_path is not None: 54 | fileHandler = logging.FileHandler(get_config().log_path) 55 | fileHandler.setFormatter(log_formatter) 56 | logger.addHandler(fileHandler) 57 | 58 | consoleHandler = logging.StreamHandler() 59 | consoleHandler.setFormatter(log_formatter) 60 | logger.addHandler(consoleHandler) 61 | 62 | logger.setLevel(get_config().log_level) 63 | 64 | logging.getLogger('telegram').setLevel(logging.INFO) 65 | 66 | # ================== BOT ================== 67 | updater = Updater(get_config().telegram_token) 68 | load_dispatcher(updater.dispatcher) 69 | set_bot(updater.bot) 70 | 71 | # Start the Bot 72 | updater.start_polling(timeout=15, read_latency=6) 73 | logging.error("Bot started") 74 | init_email_service() 75 | 76 | # Run the bot until the user presses Ctrl-C or the process receives SIGINT, 77 | # SIGTERM or SIGABRT 78 | updater.idle() 79 | logging.error("Bye !") 80 | 81 | 82 | if __name__ == '__main__': 83 | init() 84 | -------------------------------------------------------------------------------- /repository/account.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | from config.loadConfig import get_config 18 | 19 | 20 | def parse_accounts_to_json(accounts): 21 | json = [] 22 | for acc in accounts: 23 | account = {'name': acc.name, 'username': acc.username, 'password': acc.password, 'host': acc.host, 24 | 'port': acc.port, 'protocol': acc.protocol, 'refresh_time': acc.refresh_time} 25 | json.append(account) 26 | return json 27 | 28 | 29 | def parse_json_to_accounts(accounts): 30 | result = [] 31 | for acc in accounts: 32 | account = Account(acc['name'],acc['username'],acc['password'], acc['host'], acc['port'], 33 | acc['protocol'], acc['refresh_time']) 34 | result.append(account) 35 | return result 36 | 37 | 38 | class Account: 39 | def __init__(self, name, username, password, host, port, protocol, refresh_time=None): 40 | self.name = name 41 | self.username = username 42 | self.password = password 43 | self.host = host 44 | self.port = port 45 | self.protocol = protocol 46 | if refresh_time is None: 47 | self.refresh_time = get_config().default_refresh_inbox 48 | else: 49 | self.refresh_time = refresh_time 50 | -------------------------------------------------------------------------------- /repository/email_server.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | class EmailServer: 18 | def __init__(self, name, host, port, protocol): 19 | self.name = name 20 | self.host = host 21 | self.port = port 22 | self.protocol = protocol 23 | -------------------------------------------------------------------------------- /repository/repository.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | import os 18 | from tinydb import TinyDB, Query 19 | from repository.email_server import EmailServer 20 | from repository.user import User 21 | from repository.account import parse_accounts_to_json, parse_json_to_accounts 22 | 23 | 24 | db = None 25 | 26 | 27 | def get_dbc(): 28 | return db 29 | 30 | 31 | def set_dbc(dbc): 32 | global db 33 | db = dbc 34 | 35 | 36 | class DBC: 37 | def __init__(self, path=None): 38 | if path is None: 39 | self.db = TinyDB(os.path.join('config', 'tmail-bot.json')) 40 | else: 41 | self.db = TinyDB(path) 42 | 43 | def get_table(self, table_name): 44 | return self.db.table(table_name) 45 | 46 | def purge(self): 47 | self.db.purge_tables() 48 | 49 | def insert_email_server(self, name, host, port, protocol): 50 | email_servers = self.db.table('EmailServers') 51 | email_servers.insert({'name': name, 'host': host, 'port': port, 'protocol': protocol}) 52 | return EmailServer(name, host, port, protocol) 53 | 54 | def search_email_server(self, name, protocol): 55 | email_servers = self.db.table('EmailServers') 56 | query = Query() 57 | search = email_servers.search(query.name == name and query.protocol == protocol) 58 | result = eval(str(search))[0] # We suppose that names + protocol will be unique 59 | email_server = EmailServer(name, result['host'], result['port'], result['protocol']) 60 | return email_server 61 | 62 | def update_email_server(self, email_server): 63 | email_servers = self.db.table('EmailServers') 64 | query = Query() 65 | email_servers.update({'host': email_server.host, 'port': email_server.port}, 66 | query.name == email_server.name and query.protocol == email_server.protocol) 67 | 68 | def remove_email_server(self, name, protocol): 69 | email_servers = self.db.table('EmailServers') 70 | query = Query() 71 | email_servers.remove(query.name == name and query.protocol == protocol) 72 | 73 | def insert_user(self, id, accounts): 74 | users = self.db.table('Users') 75 | users.insert({'id': id, 'accounts': parse_accounts_to_json(accounts)}) 76 | return User(id, accounts) 77 | 78 | def search_user(self, id): 79 | users = self.db.table('Users') 80 | query = Query() 81 | search = users.search(query.id == id) 82 | result = eval(str(search))[0] 83 | user = User(id, parse_json_to_accounts(result['accounts'])) 84 | return user 85 | 86 | def update_user(self, user): 87 | users = self.db.table('Users') 88 | query = Query() 89 | users.update({'id': user.id, 'accounts': parse_accounts_to_json(user.accounts)}, 90 | query.id == user.id) 91 | 92 | def get_all_users(self): 93 | users = self.db.table('Users') 94 | res = [] 95 | for a in users.all(): 96 | res.append(User(a['id'], parse_json_to_accounts(a['accounts']))) 97 | return res 98 | 99 | def remove_user(self, user_id): 100 | users = self.db.table('Users') 101 | query = Query() 102 | users.remove(query.id == user_id) 103 | 104 | def get_accounts_of_user(self, user): 105 | user = self.search_user(user.id) 106 | return user.accounts 107 | 108 | def get_account_of_user(self, user, username): 109 | user = self.search_user(user.id) 110 | result = None 111 | for account in user.accounts: 112 | if account.username == username: 113 | result = account 114 | break 115 | return result 116 | 117 | def add_account_to_user(self, user, account): 118 | user = self.search_user(user.id) 119 | user.add_account(account) 120 | self.update_user(user) 121 | 122 | def update_account_of_user(self, user, account): 123 | user = self.search_user(user.id) 124 | user.update_account(account) 125 | self.update_user(user) 126 | 127 | def remove_account_of_user(self, user, account): 128 | user = self.search_user(user.id) 129 | user.remove_account(account) 130 | self.update_user(user) 131 | 132 | def get_email_server_of_account(self, account, protocol): 133 | email_server = self.search_email_server(account.name, protocol) 134 | return email_server 135 | -------------------------------------------------------------------------------- /repository/user.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | class User: 18 | def __init__(self, id, accounts): 19 | self.id = id 20 | self.accounts = accounts 21 | 22 | def add_account(self, account): 23 | self.accounts.append(account) 24 | 25 | def update_account(self, account): 26 | i = 0 27 | for acc in self.accounts: 28 | if acc.name == account.name: 29 | self.accounts[i] = account 30 | break 31 | i = i + 1 32 | 33 | def remove_account(self, account): 34 | i = 0 35 | for acc in self.accounts: 36 | if acc.name == account.name: 37 | self.accounts.pop(i) 38 | break 39 | i = i + 1 40 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-telegram-bot==8.0 2 | click 3 | tinydb==3.5.0 4 | pytz==2017.2 5 | schedule==0.4.3 6 | beautifulsoup4 7 | -------------------------------------------------------------------------------- /services/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | bot = None 18 | emailsServices = dict() 19 | 20 | def get_bot(): 21 | return bot 22 | 23 | def set_bot(inp): 24 | global bot 25 | bot = inp 26 | 27 | 28 | def get_emails_servers(): 29 | return emailsServices 30 | 31 | def get_email_server(inp): 32 | return emailsServices[inp] 33 | 34 | def add_email_server(key, value): 35 | emailsServices[key] = value 36 | 37 | -------------------------------------------------------------------------------- /services/email.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | from utils.telegram import notify_new_email 18 | import repository.repository as repository 19 | from config.loadConfig import get_config 20 | import utils.imap as imap_util 21 | import logging 22 | import schedule 23 | from repository.repository import get_dbc 24 | from services import get_bot, get_email_server, add_email_server 25 | import os 26 | import sys 27 | 28 | 29 | def init_email_service(): 30 | users = get_dbc().get_all_users() 31 | 32 | if not users: 33 | return 34 | 35 | for u in users: 36 | for a in u.accounts: 37 | add_email_server(a.username, EmailService(u.id, a, {'inbox': None})) 38 | get_email_server(a.username).schedule(a.refresh_time) 39 | get_email_server(a.username).check('inbox') 40 | 41 | 42 | class EmailService: 43 | def __init__(self, id_user, account, folder_last_message_uid): 44 | self.__user = id_user 45 | self.__account = account 46 | 47 | self.__connect() 48 | 49 | self.folder_last_message_uid = dict() 50 | 51 | for folder, uid in folder_last_message_uid.items(): 52 | if uid is not None: 53 | self.folder_last_message_uid[folder] = uid 54 | continue 55 | uids, err = imap_util.get_uid_list(self.mail, folder) 56 | if err is not None: 57 | logging.error("Error reading folder: " + str(err)) 58 | continue 59 | self.folder_last_message_uid[folder] = int(uids[-2]) # for debug 60 | # self.folder_last_message_uid[folder] = int(uids[-1]) 61 | # self.folder_last_message_uid[folder] = None # Initially empty email 62 | 63 | def __connect(self): 64 | logging.debug("Reconnecting account: " + self.__user) 65 | # db = repository.DBC(get_config().db_path) 66 | # account = db.get_accounts_of_user(db.search_user(get_config().telegram_admin_user_id))[0] 67 | # email_server = db.search_email_server(self.__nameServer, self.__protocol) 68 | # message_content = email_repo.get_message_content(self.__user, self.__email) 69 | self.mail = imap_util.connect(self.__account.host, self.__account.port, 70 | self.__account.username, self.__account.password) 71 | self.mail.select('inbox') 72 | 73 | def check(self, folder): 74 | logging.debug("Checking account: " + self.__account.username + ":/" + folder) 75 | try: 76 | if not self.__check_alive(): 77 | self.__connect() 78 | 79 | self.read_email_from_gmail(folder) 80 | except Exception as e: 81 | logging.error("Failed checkin email account") 82 | logging.error(e) 83 | exc_type, exc_obj, exc_tb = sys.exc_info() 84 | f_name = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] 85 | logging.error(exc_type, f_name, exc_tb.tb_lineno) 86 | get_bot().send_message(chat_id=self.__user, parse_mode="Markdown", 87 | text="Something go really bad. You couldn't be notify of news emails on account " 88 | + self.__account.username) 89 | 90 | def schedule(self, time_seconds): 91 | schedule.every(time_seconds).seconds.do(self.check, 'inbox')\ 92 | .tag('checkemail', 93 | self.__account.username.partition("@")[0], 94 | self.__account.protocol) 95 | 96 | def read_email_from_gmail(self, folder): 97 | uids, err = self.__get_uid_list(folder) 98 | logging.info("Emails in folder: " + str(len(uids))) 99 | if len(uids) < 1: 100 | return 101 | most_recent_uid = int(uids[-1]) 102 | 103 | if most_recent_uid == self.folder_last_message_uid[folder]: 104 | return 105 | 106 | uids_truncated = [] 107 | for uid in reversed(uids): 108 | try: 109 | if int(uid) <= self.folder_last_message_uid[folder]: 110 | break 111 | except: 112 | pass 113 | uids_truncated.append(uid) 114 | 115 | for uid in reversed(uids_truncated): 116 | msg = self.get_email_by_uid(folder, uid) 117 | notify_new_email(get_bot(), self.__user, msg) 118 | self.folder_last_message_uid[folder] = most_recent_uid 119 | 120 | def mark_as_read(self, folder, uid, mark_as_read=True): 121 | if not self.__check_alive(): 122 | self.__connect() 123 | put_or_quit = '+' 124 | if not mark_as_read: 125 | put_or_quit = '-' 126 | imap_util.change_flags(self.mail, folder, uid, flag='Seen', put_or_quit=put_or_quit) 127 | 128 | def __get_uid_list(self, folder): 129 | return imap_util.get_uid_list(self.mail, folder) 130 | 131 | def get_email_by_uid(self, folder, uid): 132 | if not self.__check_alive(): 133 | self.__connect() 134 | return imap_util.get_email_by_uid(self.mail, folder, uid) 135 | 136 | def __check_alive(self): 137 | try: 138 | status = self.mail.noop()[0] 139 | except: # smtplib.SMTPServerDisconnected 140 | status = -1 141 | return True if status == "OK" else False 142 | 143 | def add_to_folder(self, uid, from_folder, to_folder): 144 | if not self.__check_alive(): 145 | self.__connect() 146 | try: 147 | imap_util.add_message_to_folder(self.mail, uid, from_folder, to_folder) 148 | except: 149 | logging.error("Failed adding to folder") 150 | 151 | def delete_from_folder(self, uid, folder): 152 | if not self.__check_alive(): 153 | self.__connect() 154 | try: 155 | imap_util.remove_message_from_folder(self.mail, uid, folder) 156 | except Exception as e: 157 | logging.error("Failed removing from folder") 158 | logging.error(e) 159 | 160 | def get_folders(self): 161 | if not self.__check_alive(): 162 | self.__connect() 163 | return imap_util.get_folders(self.mail) 164 | 165 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . -------------------------------------------------------------------------------- /tests/accountTest.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | import os 18 | 19 | from repository.repository import DBC 20 | from repository.account import Account, parse_accounts_to_json 21 | 22 | db = DBC(os.path.join('..', 'config', 'tmail-bot.json')) 23 | 24 | # Test Accounts 25 | 26 | account1 = Account('Gmail', 'test@gmail.com', 'mypass', 'test.com', 465, 'IMAP', 15) 27 | account2 = Account('Outlook', 'test@outlook.com', 'mypass', 'test.com', 465, 'IMAP', 25) 28 | accounts = [account1, account2] 29 | db.insert_user('123456789', accounts) 30 | User = db.search_user('123456789') 31 | account3 = Account('Gmail', 'test@gmail.com', 'mypass', 'test.com', 465, 'IMAP', 15) 32 | account4 = Account('Outlook', 'test@outlook.com', 'mypass', 'test.com', 465, 'IMAP', 25) 33 | accounts = [account3] 34 | db.insert_user('123456789', accounts) 35 | User1 = db.search_user('123456789') 36 | print('\n[' + User1.id + ']\nAccounts: ' + str(parse_accounts_to_json(User1.accounts))) 37 | db.add_account_to_user(User, account4) 38 | User1 = db.search_user('123456789') 39 | print('\n[' + User1.id + ']\nAccounts: ' + str(parse_accounts_to_json(User1.accounts))) 40 | account4.refresh_time = 35 41 | db.update_account_of_user(User, account4) 42 | User1 = db.search_user('123456789') 43 | print('\n[' + User1.id + ']\nAccounts: ' + str(parse_accounts_to_json(User1.accounts))) 44 | db.remove_account_of_user(User, account4) 45 | User1 = db.search_user('123456789') 46 | print('\n[' + User1.id + ']\nAccounts: ' + str(parse_accounts_to_json(User1.accounts))) 47 | db.remove_user('123456789') 48 | -------------------------------------------------------------------------------- /tests/emailServerTest.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | import os 18 | 19 | from repository.repository import DBC 20 | 21 | #Test DATABASE utils 22 | 23 | db = DBC(os.path.join('..','config', 'tmail-bot.json')) 24 | 25 | #Test EmailServer 26 | 27 | db.insert_email_server('Gmail', 'smtp.gmail.com', 465, 'SMTP') 28 | EmailServer = db.search_email_server('Gmail', 'IMAP') 29 | print('\n['+EmailServer.name+']\nHost: '+EmailServer.host+'\nPort: '+str(EmailServer.port)+ 30 | '\nProtocol: '+EmailServer.protocol) 31 | EmailServer.port = 468 32 | db.update_email_server(EmailServer) 33 | EmailServer = db.search_email_server('Gmail', 'IMAP') 34 | print('\n['+EmailServer.name+']\nHost: '+EmailServer.host+'\nPort: '+str(EmailServer.port)+ 35 | '\nProtocol: ' + EmailServer.protocol) 36 | db.remove_email_server('Gmail', 'IMAP') 37 | -------------------------------------------------------------------------------- /tests/userTest.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | import os 18 | 19 | from repository.repository import DBC 20 | from repository.account import Account, parse_accounts_to_json 21 | 22 | # Test DATABASE utils 23 | 24 | db = DBC(os.path.join('..', 'config', 'tmail-bot.json')) 25 | 26 | # Test User 27 | 28 | account1 = Account('Gmail', 'test@gmail.com', 'mypass', 'test.com', 465, 'IMAP', 15) 29 | account2 = Account('Outlook', 'test@outlook.com', 'mypass', 'test.com', 465, 'IMAP', 25) 30 | accounts = [account1, account2] 31 | db.insert_user('123456789', accounts) 32 | User = db.search_user('123456789') 33 | print('\n[' + User.id + ']\nAccounts: ' + str(parse_accounts_to_json(User.accounts))) 34 | db.remove_user('123456789') -------------------------------------------------------------------------------- /utils/imap.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | import imaplib 18 | import logging 19 | import os, sys 20 | import email as email_lib 21 | from email.header import decode_header 22 | from bs4 import BeautifulSoup 23 | import re 24 | 25 | imaplib._MAXLINE = 100000 26 | 27 | class Message: 28 | def __init__(self, email, uid, folders, msg, flags=None): 29 | self.email = email 30 | self.uid = uid 31 | self.folders = folders 32 | self.msg = email_lib.message_from_bytes(msg[1]) 33 | try: 34 | self.flags = imaplib.ParseFlags(flags) 35 | except: 36 | self.flags = None 37 | 38 | @staticmethod 39 | def __fix_string(input): 40 | res = "" 41 | for input_mod, encoding in decode_header(input): 42 | try: 43 | is_bytes = isinstance(input_mod, bytes) 44 | if is_bytes and (encoding is None or "unknown" in encoding): 45 | result = input_mod.decode() 46 | elif is_bytes and encoding is not None: 47 | result = input_mod.decode(encoding=encoding) 48 | elif isinstance(input_mod, str): 49 | result = input_mod 50 | else: 51 | result = input_mod.decode(encoding) 52 | except AttributeError as ae: 53 | result = str(input_mod) 54 | pass 55 | except Exception as e: 56 | logging.error(e) 57 | logging.error(str(input_mod)) 58 | result = str(input_mod) 59 | res = res + result + " " 60 | return res 61 | 62 | def get_header(self, property): 63 | return self.__fix_string(self.msg[property]) 64 | 65 | def get_flag(self, property=None): 66 | if not property or not self.flags: 67 | return False 68 | return bytes("\\" + property, 'utf-8') in self.flags 69 | 70 | def get_body(self): 71 | maintype = self.msg.get_content_maintype() 72 | if maintype == 'multipart': 73 | html_body = None 74 | for part in self.msg.get_payload(): 75 | if part.get_content_maintype() == 'text' and part.get_content_subtype() == 'plain': 76 | return Message.__decode_body_from_part_message(part) 77 | elif part.get_content_maintype() == 'text' and part.get_content_subtype() == 'html': 78 | html_body = part 79 | elif part.get_content_maintype() == 'multipart': 80 | for part_in in part.get_payload(): 81 | if part_in.get_content_maintype() == 'text' and part_in.get_content_subtype() == 'plain': 82 | return Message.__decode_body_from_part_message(part_in) 83 | elif part.get_content_maintype() == 'text' and part_in.get_content_subtype() == 'html': 84 | html_body = part 85 | else: 86 | if html_body is not None: 87 | return Message.__decode_body_from_part_message(html_body, is_html=True) 88 | else: 89 | return "😥🙃 no compatible format found" 90 | 91 | elif maintype == 'text': 92 | return Message.__decode_body_from_part_message(self.msg, is_html=self.msg.get_content_subtype()!="plain") 93 | 94 | @staticmethod 95 | def __decode_body_from_part_message(part_msg, is_html=False, del_double_new_line=False): 96 | encode = part_msg.get_content_charset(failobj="utf-8") 97 | if not is_html: 98 | text_decode = part_msg.get_payload(decode=True).decode(encoding=encode) 99 | else: 100 | text = re.sub(" ?\r?\n\<\/", ". 17 | import os 18 | from configparser import ConfigParser 19 | 20 | from repository.repository import DBC 21 | from repository.account import Account 22 | 23 | def populateDatabase(): 24 | 25 | # Insert Default Servers 26 | db = DBC(os.path.join('..', 'config', 'tmail-bot.json')) 27 | db.purge() 28 | db.insert_email_server('GMAIL','imap.gmail.com', '993', 'IMAP') 29 | db.insert_email_server('GMAIL', 'smtp.gmail.com', '465', 'SMTP') 30 | db.insert_email_server('OUTLOOK', 'pop3.live.com', '995', 'POP3') 31 | db.insert_email_server('OUTLOOK', 'smtp.live.com', '587', 'SMTP') 32 | 33 | #Insert Test Config 34 | 35 | config = ConfigParser() 36 | config.read(os.path.join('..', 'config', 'myconfig.ini')) 37 | db.insert_email_server('Test', config['email test']['SMTP_SERVER'], config['email test']['SMTP_SERVER_PORT'] 38 | , 'SMTP') 39 | account = Account('Test',config['email test']['FROM_EMAIL'],config['email test']['FROM_PWD'], 40 | config['email test']['SMTP_SERVER'],config['email test']['SMTP_SERVER_PORT'], 'IMAP',180) 41 | db.insert_user(config['Telegram']['ADMIN_ID'], [account]) 42 | 43 | 44 | 45 | populateDatabase() 46 | -------------------------------------------------------------------------------- /utils/scheduler.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | import time 18 | import schedule 19 | import threading 20 | 21 | 22 | def init_scheduler(): 23 | cease_continuous_run = threading.Event() 24 | 25 | class ScheduleThread(threading.Thread): 26 | @classmethod 27 | def run(cls): 28 | while not cease_continuous_run.is_set(): 29 | schedule.run_pending() 30 | time.sleep(1) 31 | 32 | continuous_thread = ScheduleThread() 33 | continuous_thread.start() 34 | 35 | return cease_continuous_run 36 | -------------------------------------------------------------------------------- /utils/telegram.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 by Notmail Bot contributors. All rights reserved. 2 | # 3 | # This file is part of Notmail Bot. 4 | # 5 | # Notmail Bot is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Notmail Bot is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Notmail Bot. If not, see . 17 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 18 | import email as email_lib 19 | import time 20 | 21 | 22 | emojis = { 23 | "back": "🔙", 24 | "help": "❓", 25 | "link": "🔗", # "🌐", 26 | "mark_as_unread": "❗️", 27 | "mark_as_read": "👁", 28 | "remember": "⏰", 29 | "delete": "🗑", 30 | "details": "🔎", 31 | "archive": "🗄", # 🗃 32 | "reply": "↩", 33 | "label": "🗂", # 🏷 34 | "previous_page": "⏪", 35 | "next_page": "⏩", 36 | } 37 | 38 | 39 | def notify_new_email(bot, id_user, msg): 40 | response, reply_markup = load_main_view(msg) 41 | 42 | msg_send = bot.send_message(chat_id=id_user, parse_mode="Markdown", 43 | text=response, 44 | reply_markup=reply_markup) 45 | return msg_send is not None 46 | 47 | 48 | def load_main_view(msg, back=None): 49 | # msg = get_email_server(user_email).get_email_by_uid(folder, msg_uid) 50 | # a = msg.msg 51 | email_date = email_lib.utils.parsedate_to_datetime(msg.msg["date"]).strftime("%d %B %Y") 52 | email_from = msg.get_header('from') 53 | email_subject = msg.get_header('subject') 54 | 55 | common_sufix = '/' + msg.email + '/' + msg.uid.decode() + '/' + msg.folders[0] 56 | 57 | if msg.get_flag("Seen"): 58 | read_button = InlineKeyboardButton(emojis["mark_as_unread"], callback_data='/email/mark_unread' + common_sufix) 59 | else: 60 | read_button = InlineKeyboardButton(emojis["mark_as_read"], callback_data='/email/mark_read' + common_sufix) 61 | 62 | if back == "details": 63 | details_button = InlineKeyboardButton(emojis["back"], callback_data='/email/back' + common_sufix) 64 | else: 65 | details_button = InlineKeyboardButton(emojis["details"], callback_data='/email/view'+common_sufix) 66 | 67 | keyboard = [[ 68 | details_button, 69 | read_button, 70 | InlineKeyboardButton(emojis["archive"], callback_data='/email/archive'+common_sufix), 71 | InlineKeyboardButton(emojis["label"], callback_data='/email/label_l/0' + common_sufix), 72 | # InlineKeyboardButton(emojis["remember"], callback_data='/email/remember'+common_sufix), 73 | # InlineKeyboardButton(emojis["link"], callback_data='/email/link' + common_sufix), 74 | # InlineKeyboardButton(emojis["reply"], callback_data='/email/reply' + common_sufix), 75 | InlineKeyboardButton(emojis["help"], callback_data='/email/help'), 76 | 77 | # ], [ 78 | # InlineKeyboardButton(emojis["delete"], callback_data='/email/delete'+common_sufix), 79 | # InlineKeyboardButton(emojis["back"], callback_data='/email/back' + common_sufix), 80 | ], ] 81 | 82 | if len(email_subject) > 500: 83 | email_subject = email_subject[:500] + " ..." 84 | 85 | response = "*"+email_subject + "*\n[" + email_from + "]\n\t\t_" + email_date+"_" 86 | 87 | return response, InlineKeyboardMarkup(keyboard) 88 | 89 | --------------------------------------------------------------------------------