Чтобы отправить письмо Gmail с помощью кода, вы можете использовать различные языки программирования и библиотеки. Ниже я приведу примеры с использованием Python, JavaScript и PHP.
Python:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_email(subject, body, to_email, from_email, password):
message = MIMEMultipart()
message['Subject'] = subject
message['From'] = from_email
message['To'] = to_email
message.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_email, password)
server.send_message(message)
server.quit()
# Example usage
subject = "Hello from Python!"
body = "This is an example email sent using Python."
to_email = "recipient@gmail.com"
from_email = "your@gmail.com"
password = "your_password"
send_email(subject, body, to_email, from_email, password)
JavaScript (Node.js):
const nodemailer = require('nodemailer');
async function sendEmail(subject, body, toEmail, fromEmail, password) {
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: fromEmail,
pass: password
}
});
let mailOptions = {
from: fromEmail,
to: toEmail,
subject: subject,
text: body
};
let info = await transporter.sendMail(mailOptions);
console.log('Message sent: %s', info.messageId);
}
// Example usage
const subject = 'Hello from JavaScript!';
const body = 'This is an example email sent using JavaScript.';
const toEmail = 'recipient@gmail.com';
const fromEmail = 'your@gmail.com';
const password = 'your_password';
sendEmail(subject, body, toEmail, fromEmail, password);
PHP:
<?php
require 'PHPMailer/PHPMailerAutoload.php';
function sendEmail($subject, $body, $toEmail, $fromEmail, $password) {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->Username = $fromEmail;
$mail->Password = $password;
$mail->setFrom($fromEmail);
$mail->addAddress($toEmail);
$mail->Subject = $subject;
$mail->Body = $body;
if (!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
}
// Example usage
$subject = 'Hello from PHP!';
$body = 'This is an example email sent using PHP.';
$toEmail = 'recipient@gmail.com';
$fromEmail = 'your@gmail.com';
$password = 'your_password';
sendEmail($subject, $body, $toEmail, $fromEmail, $password);
В этих примерах используется протокол SMTP для отправки электронных писем через SMTP-сервер Gmail. Для аутентификации вам необходимо предоставить свои учетные данные Gmail (адрес электронной почты и пароль). Обязательно замените 'your@gmail.com'и 'your_password'фактическими данными вашей учетной записи Gmail.