Jump to content

Pywikibot/Mass user mailing/Send email.py

From Wikimedia Belgium
cat send_email.py
#!/usr/bin/python3

"""
Author: Geert Van Pamel, 2020-01-22, CC BY-SA 4.0, User:Geertivp

Send an e-mail to a list of Wikimedia users.
"""

import pywikibot
from datetime import datetime	# now, strftime, delta time, total_seconds

mailto = """
(list of usernames, one per line)
"""

mailsubject = 'Wiki Loves Heritage Belgium 2020'
mailbody = """Dear participant of Wiki Loves Heritage Belgium 2020,
(rest of body text)

-- Geert Van Pamel, Wikimedia Belgium
"""

# Login to Wikimedia account
site = pywikibot.Site('be', 'wikimedia')
site.login()    # Must login to send email
account = pywikibot.User(site, site.user())

try:    # Old accounts do not have a registration date
    print ('Account:', site.user(), account.registration().strftime('%Y-%m-%d'), account.groups())
except Exception:
    print ('Account:', site.user(), account.groups())

mailcnt = 0
mailerr = 0

for user in sorted(set(mailto.split('\n'))):
  if user != '':
    try:
        wikiuser = pywikibot.User(site, user)
        mailstat = wikiuser.send_email(subject=mailsubject, text=mailbody)
        print(user)
        mailcnt += 1
    except Exception as error:
        print('Error sending to %s,' % (user), format(error))
        mailerr += 1

print('%d mails sent\n%d failed' % (mailcnt, mailerr))

Known problems

[edit]
You don't have permission to send mail
Please login before attempting to send mail
WARNING - API error ratelimited - As an anti-abuse measure, you are limited from performing this action too many times in a short space of time, and you have exceeded this limit. Please try again in a few minutes.
Use an account that has the noratelimit right
HTML mail not supported
Fallback to plain text instead

Tips

[edit]
  • add your own username to the list (to have a copy of the message)
  • first send a test e-mail only to yourself
  • verify the result before running the mass mailing
  • send messages in the language of the users (group the distribution list per language)
  • use the script command to create a log file typescript