Telegram机器人邮件转发实现及SMTP密码获取方案咨询
问题解决方案
一、简化SMTP专用密码获取的方案
不同主流邮箱服务商的专用密码/授权码获取步骤已做简化,用户仅需1-3步即可完成:
- Gmail:开启两步验证后,在Google账户「安全性」页面找到「应用专用密码」,输入设备名称(如Telegram Bot)即可生成一次性专用密码。
- Outlook/Hotmail:开启两步验证后,在微软账户「安全」板块生成「应用密码」,直接用于SMTP登录。
- QQ邮箱/网易邮箱:在邮箱设置的「账户」选项中,开启「POP3/SMTP服务」即可获取授权码,此授权码即为SMTP专用密码。
二、Python实现方案
结合python-telegram-bot库实现Telegram机器人,同时优化SMTP发送逻辑:
import smtplib from email.mime.text import MIMEText from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes # 配置信息(替换为实际值) TELEGRAM_BOT_TOKEN = "你的机器人Token" SMTP_SERVER = "smtp.gmail.com" SMTP_PORT = 587 SMTP_USERNAME = "你的邮箱地址" SMTP_PASSWORD = "你的SMTP专用密码/授权码" TARGET_EMAIL = "Example@platform.gov.ru" # 存储用户输入的临时数据 user_data = {} async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("请输入你的个人邮箱:") user_data[update.effective_user.id] = {"step": "email"} async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): user_id = update.effective_user.id current_step = user_data.get(user_id, {}).get("step") if current_step == "email": user_data[user_id]["email"] = update.message.text await update.message.reply_text("请输入邮件主题:") user_data[user_id]["step"] = "subject" elif current_step == "subject": user_data[user_id]["subject"] = update.message.text await update.message.reply_text("请输入邮件内容:") user_data[user_id]["step"] = "message" elif current_step == "message": user_data[user_id]["message"] = update.message.text # 发送邮件 try: send_email(user_data[user_id]["email"], TARGET_EMAIL, user_data[user_id]["subject"], user_data[user_id]["message"]) await update.message.reply_text("邮件已成功发送!") except Exception as e: await update.message.reply_text(f"邮件发送失败:{str(e)}") # 清空用户临时数据 del user_data[user_id] def send_email(sender_email, recipient_email, subject, message): msg = MIMEText(message) msg['Subject'] = subject msg['From'] = sender_email msg['To'] = recipient_email with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server: server.starttls() server.login(SMTP_USERNAME, SMTP_PASSWORD) server.send_message(msg) if __name__ == "__main__": application = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build() application.add_handler(CommandHandler("start", start)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) application.run_polling()
说明
- 机器人通过
/start命令引导用户依次输入邮箱、主题、内容 - 固定收件人为
Example@platform.gov.ru,无需用户手动输入 - 替换配置项中的机器人Token、SMTP信息即可直接运行
三、Java实现方案
使用java-telegram-bot-api和JavaMail API实现:
Maven依赖
<dependencies> <dependency> <groupId>org.telegram</groupId> <artifactId>telegrambots</artifactId> <version>6.9.7</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency> </dependencies>
代码实现
import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class EmailForwardBot extends TelegramLongPollingBot { private static final String BOT_TOKEN = "你的机器人Token"; private static final String BOT_USERNAME = "你的机器人用户名"; private static final String SMTP_SERVER = "smtp.gmail.com"; private static final int SMTP_PORT = 587; private static final String SMTP_USER = "你的邮箱地址"; private static final String SMTP_PASS = "你的SMTP专用密码/授权码"; private static final String TARGET_EMAIL = "Example@platform.gov.ru"; private Map<Long, UserInput> userInputMap = new HashMap<>(); private enum Step {EMAIL, SUBJECT, MESSAGE} private static class UserInput { Step currentStep; String email; String subject; String message; } @Override public String getBotUsername() { return BOT_USERNAME; } @Override public String getBotToken() { return BOT_TOKEN; } @Override public void onUpdateReceived(Update update) { if (update.hasMessage() && update.getMessage().hasText()) { long chatId = update.getMessage().getChatId(); String text = update.getMessage().getText(); if (text.equals("/start")) { UserInput input = new UserInput(); input.currentStep = Step.EMAIL; userInputMap.put(chatId, input); sendMessage(chatId, "请输入你的个人邮箱:"); return; } UserInput input = userInputMap.get(chatId); if (input == null) { sendMessage(chatId, "请先发送/start开始流程"); return; } switch (input.currentStep) { case EMAIL: input.email = text; input.currentStep = Step.SUBJECT; sendMessage(chatId, "请输入邮件主题:"); break; case SUBJECT: input.subject = text; input.currentStep = Step.MESSAGE; sendMessage(chatId, "请输入邮件内容:"); break; case MESSAGE: input.message = text; try { sendEmail(input.email, TARGET_EMAIL, input.subject, input.message); sendMessage(chatId, "邮件已成功发送!"); } catch (MessagingException e) { sendMessage(chatId, "邮件发送失败:" + e.getMessage()); } userInputMap.remove(chatId); break; } } } private void sendEmail(String sender, String recipient, String subject, String content) throws MessagingException { Properties props = new Properties(); props.put("mail.smtp.host", SMTP_SERVER); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(SMTP_USER, SMTP_PASS); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); message.setSubject(subject); message.setText(content); Transport.send(message); } private void sendMessage(long chatId, String text) { SendMessage message = new SendMessage(); message.setChatId(chatId); message.setText(text); try { execute(message); } catch (TelegramApiException e) { e.printStackTrace(); } } public static void main(String[] args) { org.telegram.telegrambots.meta.TelegramBotsApi botsApi; try { botsApi = new org.telegram.telegrambots.meta.TelegramBotsApi(org.telegram.telegrambots.updatesreceivers.DefaultBotSession.class); botsApi.registerBot(new EmailForwardBot()); } catch (TelegramApiException e) { e.printStackTrace(); } } }
说明
- 通过
/start命令启动流程,引导用户逐步输入信息 - 封装SMTP发送逻辑,替换配置项即可运行
内容的提问来源于stack exchange,提问作者Andrey
相关产品推荐
相关产品推荐

