google邮箱 发送

本文介绍了如何申请Google邮箱账号,配置POP/IMAP,创建应用密码以确保安全,并利用PHPMailer库在PHP中设置SMTP进行邮件发送,特别强调了在使用国外服务器时的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

google邮箱 发送

前期准备
一、申请google 邮箱账号 https://mail.google.com/
二、配置google 邮箱开启 pop/imap

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

三、创建应用密码,发送验证码时填写此密码
Create & use app passwords
Important: To create an app password, you need 2-Step Verification on your Google Account.

If you use 2-Step-Verification and get a “password incorrect” error when you sign in, you can try to use an app password.

Go to your Google Account.
Select Security.
Under “How you sign in to Google,” select 2-Step Verification.
At the bottom of the page, select App passwords.
Enter a name that helps you remember where you’ll use the app password.
Select Generate.
To enter the app password, follow the instructions on your screen. The app password is the 16-character code that generates on your device.
Select Done.
If you’ve set up 2-Step Verification but can’t find the option to add an app password, it might be because:

Your Google Account has 2-Step Verification set up only for security keys.
You’re logged into a work, school, or another organization account.
Your Google Account has Advanced Protection.
Tip: Usually, you’ll need to enter an app password once per app or device.
四、代码编辑
引用 PHPMailer

	//端口配置
	 $Host = "smtp.gmail.com";
	 $SMTPSecure = "ssl";
	 $Port = 465;
	 
     $mail = new \PHPMailer(); //实例化
     $mail->IsSMTP(); // 启用SMTP 
      $mail->SMTPDebug = 1;
      $mail->Host = $Host; //SMTP服务器 以163邮箱为例子
      $mail->SMTPSecure = $SMTPSecure;
      $mail->Port = $Port;  //邮件发送端口
      $mail->SMTPAuth = true;  //启用SMTP认证
      $mail->CharSet = "UTF-8"; //字符集
      $mail->Encoding = "base64"; //编码方式 
      $mail->Username = $this->web_email;  //你的邮箱
      $mail->Password = $this->web_email_pass;  //你的密码
      $mail->Subject = $title; //邮件标题
      $mail->From = $this->web_email;  //发件人地址(也就是你的邮箱)
      $mail->FromName = "";  //发件人姓名
      $mail->AddAddress($user_email, "");//添加收件人(地址,昵称)
      //$mail->AddAttachment($path,'投稿附件.'.$filetype);
      //$mail->AddAttachment('投稿附件.docx',$name); // 添加附件,并指定名称
      $mail->IsHTML(true); //支持html格式内容
      //$mail->AddEmbeddedImage("logo.jpg", "my-attach", "logo.jpg"); //设置邮件中的图片
      $text = $content;
      $mail->Body = $text;
      $result = $mail->Send();

特别注意,服务器使用国外服务器

### 如何使用 Gmail 发送电子邮件 要通过 Gmail 使用应用程序发送电子邮件,可以按照以下方法实现。以下是基于 .NET Core 和 Python 的两种常见解决方案。 #### 方法一:在 .NET Core 中使用 Gmail 发送邮件 为了在 .NET Core 应用程序中成功发送电子邮件,需要完成以下几个步骤: 1. **配置 Gmail 帐号的安全设置** 如果希望简化开发过程,则可以通过启用“低安全性应用”的访问权限来快速测试功能[^2]。然而,这种方法并不推荐用于生产环境,因为存在安全隐患。对于更高的安全性,建议采用 OAuth 2.0 授权机制,尽管这会增加一些复杂度。 2. **编写代码逻辑** 下面是一个简单的 C# 实现示例,展示如何利用 `System.Net.Mail` 类库向目标地址发送邮件: ```csharp using System; using System.Net; using System.Net.Mail; public class EmailSender { public static void SendEmail(string recipient, string subject, string body) { var senderAddress = new MailAddress("your-email@gmail.com", "Your Name"); var credentials = new NetworkCredential("your-email@gmail.com", "your-password"); using (var smtpClient = new SmtpClient("smtp.gmail.com") { Port = 587, Credentials = credentials, EnableSsl = true }) { using (var mailMessage = new MailMessage(senderAddress.Address, recipient)) { mailMessage.Subject = subject; mailMessage.Body = body; try { smtpClient.Send(mailMessage); Console.WriteLine("Email sent successfully."); } catch (Exception ex) { Console.WriteLine($"Failed to send email: {ex.Message}"); } } } } public static void Main() { SendEmail("[email protected]", "Test Subject", "This is the test email content."); } } ``` 注意,在上述代码片段中的 `"your-email@gmail.com"` 和 `"your-password"` 需替换为实际使用的 Gmail 地址及其对应密码或专用应用密码(如果启用了双因素身份验证)。 --- #### 方法二:Python 中使用 Google API 或 SMTP 协议发送邮件 另一种常见的做法是在 Python 环境下操作。这里提供两个选项——直接调用 Gmail 提供的服务端点以及传统的 SMTP 方式。 ##### A. 利用 Google APIs 客户端库构建服务对象并通过其提交请求 此途径涉及创建项目、开启必要的 API 访问权能等一系列前期准备工作。下面给出一段核心处理部分的脚本作为参考[^4]: ```python from google.oauth2.credentials import Credentials import base64 from email.mime.text import MIMEText from googleapiclient.discovery import build def create_gmail_service(): creds = None # Load your credential file here or initialize it properly. SCOPES = ['https://www.googleapis.com/auth/gmail.send'] if not creds or not creds.valid: raise Exception('Credentials are missing or invalid.') service = build('gmail', 'v1', credentials=creds) return service def send_email(to_address, subject, message_text): mime_msg = MIMEText(message_text, 'plain') mime_msg['to'] = to_address mime_msg['subject'] = subject encoded_message = {'raw': base64.urlsafe_b64encode(mime_msg.as_bytes()).decode()} service = create_gmail_service() result = service.users().messages().send(userId="me", body=encoded_message).execute() print(f'Sent an email with ID: {result["id"]}') if __name__ == '__main__': send_email('[email protected]', 'Subject Line Here', 'Body of the email goes here.') ``` ##### B. 继续沿用经典的 SMTP 连接模式 相比而言,这种方式更加直观易懂,适合初学者尝试学习阶段的需求[^3]。 ```python import smtplib from email.mime.text import MIMEText def send_smtp_email(recipient, subject, body): sender = 'your-email@gmail.com' password = 'your-app-specific-password' msg = MIMEText(body, 'plain') msg['From'] = sender msg['To'] = recipient msg['Subject'] = subject server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.login(sender, password) try: server.sendmail(sender, [recipient], msg.as_string()) print("Email has been sent!") except Exception as e: print(e) finally: server.quit() if __name__ == "__main__": send_smtp_email('[email protected]', 'Testing SMTP', 'Hello from Python!') ``` 同样地,请记得更新占位符字段以匹配个人具体情况下的真实数据源信息。 --- #### 注意事项 无论选用哪种技术栈路径实施集成方案设计工作流程之前都应当仔细阅读官方文档说明材料确保遵循最新的最佳实践指南规定条款内容要求条件限制范围边界等方面的知识要点[^1]^[]^.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值