Skip to content

Email Sender

Common Email SMTP Configuration and Authorization Code Setup

Below are the SMTP server parameters and authorization code setup methods for mainstream email providers (QQ, 163, Outlook, Gmail) for quick configuration.

Email Type SMTP Server Port Encryption Username Password Type
QQ Email smtp.qq.com 465 SSL Full email address Authorization code
163 Email smtp.163.com 465 SSL Full email address Authorization code
Gmail smtp.gmail.com 587 TLS Full email address App Password

QQ Email

  1. Log in to QQ Email web version, click "Settings" > "Account" in the top right corner.
  2. Under "POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV Services", check "Enable SMTP Service" and save.
  3. Follow the prompts for mobile verification to get the authorization code (this code is the SMTP login password).
  4. When configuring email client, use the full email address as username and authorization code as password.
  5. Official documentation: QQ Email Help Center
  6. Microsoft official guide for connecting QQ Email to Outlook (including authorization code setup): View

163 Email

  1. Log in to 163 Email web version, click "Settings" > "POP3/SMTP/IMAP".
  2. Enable "SMTP Service", follow prompts for verification if required.
  3. Get the authorization code (some accounts require mobile verification), this code is the SMTP login password.
  4. When configuring email client, use the full email address as username and authorization code as password.
  5. Official help center: NetEase Email Help
  6. Reference blog: Mailbird 163 Email Configuration

Gmail

  1. Log in to your Google Account at Google Account Settings.
  2. Navigate to "Security" > "2-Step Verification" and enable 2-Factor Authentication if not already enabled.
  3. Go to "Security" > "App passwords" and generate a new app password:
  4. Select "Mail" as the app type
  5. Choose your device or enter a custom name
  6. Copy the generated 16-character password (without spaces)
  7. When configuring email client, use your full Gmail address as username and the generated App Password as password.
  8. Official documentation: Google Account Help - App passwords
  9. Gmail SMTP settings: Gmail IMAP and SMTP settings

FAQ

Q1: What is an authorization code/app-specific password? A: An authorization code/app-specific password is a special password generated by email service providers to enhance security, used for third-party applications (such as email clients, automation scripts) to log into the mailbox. It cannot be replaced by regular login passwords.

Q2: Why use authorization codes/app-specific passwords? A: After enabling two-factor authentication, regular passwords cannot be directly used for SMTP and other third-party services. Authorization codes/app-specific passwords must be used to ensure account security.

Q3: What to do if authorization code/app-specific password is lost? A: You can regenerate new authorization codes/app-specific passwords in the mailbox security settings at any time, and the old ones can be revoked.

Q4: What are common reasons for configuration failures? A: Common reasons include not enabling SMTP service, not using authorization codes/app-specific passwords, incorrect port/encryption configuration, restricted mailbox login, etc.

For specific issues, it's recommended to consult the official help centers of respective email providers or contact email service customer support.


The EmailSender module provides a complete and easy-to-use email sending solution with built-in support for multiple mainstream email service providers.

Sender Base Class

All concrete senders inherit from the EmailSender abstract base class.

EmailSender(username, password, use_tls=True, smtp_server=None, smtp_port=None, *args, **kwargs)

Bases: ABC

Email sender abstract base class.

Defines the standard interface for sending emails, all specific email service provider implementations must inherit from this class. This base class handles common email construction and sending logic, subclasses only need to provide service-specific SMTP server addresses and port numbers.

Attributes:

Name Type Description
username str

Email username (usually the complete email address).

password str

Email password or authorization code/app password.

use_tls bool

Whether to use TLS encrypted connection.

smtp_server str

SMTP server address.

smtp_port int

SMTP server port.

Raises:

Type Description
ValueError

If username or password is empty.

Initialize email sender.

Parameters:

Name Type Description Default
username str

Email username/email address

required
password str

Email password or authorization code

required
use_tls bool

Whether to use TLS encrypted connection, defaults to True

True
smtp_server str | None

SMTP server address, if not provided, uses default value

None
smtp_port int | None

SMTP server port, if not provided, uses default value

None
*args Any

Other positional arguments

()
**kwargs Any

Other keyword arguments

{}

Raises:

Type Description
ValueError

Raised when username or password is empty

Functions

send(email, sender=None, to=None)

Send email.

Parameters:

Name Type Description Default
email Email

Email object to send

required
sender str | None

Sender email address, uses username if None

None
to list[str] | None

Recipient email address list, sends to sender if None

None

Raises:

Type Description
ValueError

Raised when email object is None

SMTPException

SMTP sending error

Exception

Other sending errors

Examples:

Python Console Session
>>> sender = QQEmailSender("user@qq.com", "password")
>>> email = Email("Test Email")
>>>
>>> # Send to self
>>> sender.send(email)
>>>
>>> # Send to specified recipients
>>> sender.send(email, to=["recipient@example.com"])
>>>
>>> # Specify sender and recipients
>>> sender.send(email, sender="custom@qq.com", to=["recipient@example.com"])

Factory Function

For convenience, we recommend using the create_email_sender factory function to create sender instances.

create_email_sender(provider, username, password, **kwargs)

Factory function to quickly create corresponding email sender instances based on provider name.

This is a convenient helper function that allows you to avoid directly importing and instantiating specific sender classes. It selects the correct sender through a string identifier, particularly suitable for scenarios where the provider is specified in configuration files.

Parameters:

Name Type Description Default
provider str

Email provider identifier. Supported values (case-insensitive) include: 'qq', 'netease', '163', '126', 'gmail'.

required
username str

Email account, usually the complete email address.

required
password str

Email authorization code or app password.

required
**kwargs Any

Other keyword arguments, will be passed directly to the selected sender class constructor.

{}

Returns:

Name Type Description
EmailSender EmailSender

A concrete email sender instance (e.g. QQEmailSender).

Raises:

Type Description
ValueError

If the provided provider name is not supported.

Examples:

Python
from email_widget import Email, create_email_sender
import os

# Read provider and credentials from config or environment variables
email_provider = os.getenv("EMAIL_PROVIDER", "qq") # e.g., 'qq' or 'netease'
email_user = os.getenv("EMAIL_USER")
email_password = os.getenv("EMAIL_PASSWORD")

# Create sender using factory function
try:
    sender = create_email_sender(
        provider=email_provider,
        username=email_user,
        password=email_password
    )

    email = Email(f"Email from {email_provider.upper()}")
    email.add_text("Sender created through factory function.")
    sender.send(email, to=["test@example.com"])
    print("Email sent successfully!")

except ValueError as e:
    print(f"Configuration error: {e}")
except Exception as e:
    print(f"Sending failed: {e}")

Concrete Implementations

Below are specific implementation classes for different email service providers. Usually you only need to use them through the factory function.

QQEmailSender

Bases: EmailSender

QQ Email sender.

Specifically designed for sending emails through QQ Email (including enterprise email). It presets the SMTP server address and recommended port for QQ Email.

Important notes
  • Must use authorization code: For security reasons, QQ Email's SMTP service requires using an "authorization code" instead of your login password. You need to generate this authorization code in QQ Email's "Settings" -> "Account" page.
  • Enable SMTP service: Please ensure you have enabled IMAP/SMTP service in QQ Email settings.

Examples:

Python
from email_widget import Email, QQEmailSender
import os

# Recommend reading sensitive information from environment variables
# export EMAIL_USER="your_account@qq.com"
# export EMAIL_AUTH_CODE="your_generated_auth_code"

qq_user = os.getenv("EMAIL_USER")
auth_code = os.getenv("EMAIL_AUTH_CODE")

# Create email content
email = Email("Report from QQ Email")
email.add_text("This is a test email sent through EmailWidget.")

# Initialize QQ Email sender
sender = QQEmailSender(username=qq_user, password=auth_code)

# Send email to one or more recipients
try:
    sender.send(email, to=["recipient1@example.com", "recipient2@example.com"])
    print("Email sent successfully!")
except Exception as e:
    print(f"Email sending failed: {e}")

Initialize QQ Email sender.

Parameters:

Name Type Description Default
username str

QQ Email address

required
password str

QQ Email authorization code (not login password)

required
use_tls bool

Whether to use TLS encryption, defaults to True

True
*args Any

Other positional arguments

()
**kwargs Any

Other keyword arguments

{}

NetEaseEmailSender

Bases: EmailSender

NetEase Email sender.

Supports NetEase's 163, 126, and yeah.net email services. It automatically selects the correct SMTP server based on your email address suffix.

Important notes
  • Must use authorization code: Similar to QQ Email, NetEase Email also requires using a dedicated "client authorization password" instead of your email login password.
  • Enable SMTP service: Please enable POP3/SMTP/IMAP service in your NetEase Email settings.
  • SSL connection: NetEase Email's SMTP service primarily uses SSL encryption (port 465), so the default use_tls is False.

Examples:

Python
from email_widget import Email, NetEaseEmailSender
import os

# Using 163 email
user_163 = os.getenv("NETEASE_USER_163") # e.g., "my_account@163.com"
auth_code_163 = os.getenv("NETEASE_AUTH_CODE_163")

email = Email("Greetings from 163 Email")
email.add_text("This is an email sent through NetEaseEmailSender.")

sender = NetEaseEmailSender(username=user_163, password=auth_code_163)

try:
    sender.send(email, to=["friend@example.com"])
    print("163 email sent successfully!")
except Exception as e:
    print(f"Email sending failed: {e}")

Initialize NetEase Email sender.

Parameters:

Name Type Description Default
username str

NetEase Email address

required
password str

NetEase Email authorization code

required
use_tls bool

Whether to use TLS encryption, defaults to False (NetEase Email uses SSL)

False
*args Any

Other positional arguments

()
**kwargs Any

Other keyword arguments

{}
Note

NetEase Email only supports SSL connection (port 465), recommend keeping use_tls=False.

GmailEmailSender

Bases: EmailSender

Gmail email sender.

Specifically designed for sending emails through Gmail SMTP service. It presets the SMTP server address and recommended port for Gmail.

Important notes
  • Must use App Password: For security reasons, Gmail's SMTP service requires using an "App Password" instead of your regular Gmail password. You need to:
  • Enable 2-Factor Authentication on your Google account
  • Generate an App Password in Google Account settings (Security > App passwords)
  • Less Secure App Access: Alternatively, you can enable "Less secure app access" in Gmail settings, but App Password is the recommended approach.
  • SMTP Service: Gmail SMTP service is enabled by default for all accounts.

Examples:

Python
from email_widget import Email, GmailEmailSender
import os

# Recommend reading sensitive information from environment variables
# export GMAIL_USER="your_account@gmail.com"
# export GMAIL_APP_PASSWORD="your_generated_app_password"

gmail_user = os.getenv("GMAIL_USER")
app_password = os.getenv("GMAIL_APP_PASSWORD")

# Create email content
email = Email("Report from Gmail")
email.add_text("This is a test email sent through EmailWidget via Gmail.")

# Initialize Gmail sender
sender = GmailEmailSender(username=gmail_user, password=app_password)

# Send email to one or more recipients
try:
    sender.send(email, to=["recipient1@example.com", "recipient2@example.com"])
    print("Email sent successfully!")
except Exception as e:
    print(f"Email sending failed: {e}")
Setup Instructions
  1. Enable 2-Factor Authentication:
  2. Go to Google Account settings (https://myaccount.google.com)
  3. Navigate to Security > 2-Step Verification
  4. Follow the setup process

  5. Generate App Password:

  6. Go to Security > App passwords
  7. Select "Mail" and your device
  8. Copy the generated 16-character password (without spaces)

  9. Use in EmailWidget:

  10. Use your full Gmail address as username
  11. Use the generated App Password (not your regular password)

Initialize Gmail sender.

Parameters:

Name Type Description Default
username str

Gmail address (e.g., "user@gmail.com")

required
password str

Gmail App Password (16-character generated password)

required
use_tls bool

Whether to use TLS encryption, defaults to True

True
*args Any

Other positional arguments

()
**kwargs Any

Other keyword arguments

{}
Note

Gmail supports both TLS (port 587) and SSL (port 465). TLS is recommended.