패키지, 저장소 및 앱 카테고리 검색

패키지 상세v7.3.0

mailer

Dart에서 이메일을 작성하고 보냅니다. 파일 첨부 및 HTML 이메일을 지원합니다.

AndroidiOSmacOSWindowsLinux
30일 다운로드
26.2만
좋아요
450
Pub 점수
150

패키지 설치

flutter pub add mailer

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Mailer는 Dart 애플리케이션에서 직접 이메일을 작성하고 보낼 수 있도록 해주는 Dart 패키지입니다. HTML 메일, 일반 텍스트 메시지 및 파일 첨부를 지원하여 알림, 보고서 또는 사용자 통신에 적합합니다. 간단함을 중심으로 설계되어 SMTP 서버와 원활하게 통합되며, Android, iOS, macOS, Windows, Linux 등 다양한 플랫폼에서 작동합니다. Flutter 앱에서 서버 측 또는 클라이언트 측 이메일 기능에 이상적입니다.

사용 사례

  • 트랜잭션 이메일 보내기
  • 자동 보고서 전달
  • 사용자 등록 확인
  • 첨부 파일이 있는 이메일
  • 다중 플랫폼 이메일 지원

주요 기능

  • HTML 및 일반 텍스트 이메일을 지원합니다
  • 파일 첨부 처리
  • SMTP 통합
  • 크로스 플랫폼 호환성
  • 간단한 API 설계

적합한 대상

  • 이메일 기능이 필요한 플러터 앱
  • Dart를 사용한 백엔드 서비스
  • 자동화된 이메일 워크플로우가 필요한 응용 프로그램
  • 알림 시스템을 구축하는 개발자
  • 여러 운영 체제를 대상으로 하는 프로젝트

고려 사항

  • SMTP 서버 구성이 필요합니다
  • 추가 보안 설정(TLS/SSL 등)이 필요할 수 있습니다
  • 네트워크 연결에 따라 다름
  • 고용량 대량 이메일 발송을 위한 것이 아님
  • 인증 자격 증명은 안전하게 관리되어야 합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

mailer

mailer is an easy-to-use library for composing and sending emails in Dart.

[!WARNING] This is an SMTP client library. It is designed to send emails by connecting to an existing SMTP server (like Gmail, SendGrid, Mailgun, or your own Postfix/Exim server).

It is not an SMTP server and cannot receive emails or accept incoming connections from other mail clients.

It supports:

  • Plaintext and HTML emails.
  • Attachments (files, streams, etc.).
  • Inline images (using CID).
  • Unicode support.
  • RFC 3030 (CHUNKING) for efficient large file transfer.
  • Secure connections (TLS/SSL) with context-aware sanitization.
  • Custom Address Validation strategies (strict, permissive, etc.).
  • Pre-configured services (Gmail, Yahoo, Hotmail, etc.) and generic SMTP support.

Usage

Simple Example (Gmail)
import 'package:mailer/mailer.dart';
import 'package:mailer/smtp_server.dart';

void main() async {
  String username = 'username@gmail.com';
  String password = 'password'; // Use an App Password if 2FA is enabled

  final smtpServer = gmail(username, password);
  // Use the SmtpServer class to configure any other SMTP server:
  // final smtpServer = SmtpServer('smtp.domain.com');

  final message = Message()
    ..from = Address(username, 'Your Name')
    ..recipients.add('destination@example.com')
    ..ccRecipients.addAll(['destCc1@example.com', 'destCc2@example.com'])
    ..bccRecipients.add(Address('bccAddress@example.com'))
    ..subject = 'Test Dart Mailer library :: 😀 :: ${DateTime.now()}'
    ..text = 'This is the plain text.\nThis is line 2 of the text part.'
    ..html = "<h1>Test</h1>\n<p>Hey! Here's some HTML content</p>";

  try {
    final sendReport = await send(message, smtpServer);
    print('Message sent: $sendReport');
  } on MailerException catch (e) {
    print('Message not sent.');
    for (var p in e.problems) {
      print('Problem: ${p.code}: ${p.msg}');
    }
  }
}
Advanced Usage
Attachments and Inline Images
final message = Message()
  ..from = Address(username, 'Your Name')
  ..recipients.add('destination@example.com')
  ..subject = 'Inline Image Test'
  ..html = '<h1>Test</h1><p>Here is an image:</p><img src="cid:myimg@3.141"/>'
  ..attachments = [
    FileAttachment(File('image.png'))
      ..location = Location.inline
      ..cid = '<myimg@3.141>'
  ];
Custom Address Validation

The library validates addresses before sending. By default, it uses a simple check (contains @ with non-empty parts). You can customize this behavior:

Available validators:

Validator Use Case
PracticalAddressValidator Recommended for input validation. Rejects IP literals, quoted strings, and domains without dots.
StrictAddressValidator Full RFC 5322 compliance. Accepts technically valid but uncommon formats.
PermissiveAddressValidator Accepts any non-empty string.

Validating user input (recommended):

import 'package:mailer/src/core/address_validator.dart';

final validator = PracticalAddressValidator();
final address = Address('test@example.com');

if (validator.validate(address)) {
  print('Address is valid');
} else {
  print('Address is invalid - may not be deliverable');
}

Using a validator for sending:

final message = Message()
  ..validator = StrictAddressValidator() // or PracticalAddressValidator()
  ..from = 'valid@example.com';
Persistent Connection

For sending multiple messages efficiently, use PersistentConnection.

var connection = PersistentConnection(smtpServer);

await connection.send(message1);
await connection.send(message2);

await connection.close();

Documentation

Tutorials

Flutter Developers

Flutter Web is NOT supported. Sending emails via SMTP directly from a browser is technically impossible due to security restrictions (CORS, lack of raw socket access). You must use a backend server or a proxy.

Security Warning: Do NOT embed your SMTP credentials (username/password) directly in your client-side Flutter code. If you do, anyone can extract them and use your account to send spam.

Johannes Milke has created an excellent tutorial on how to use mailer without needing to embed your credentials in the Flutter app:

The tutorial uses Firebase and requests the credentials of the Android user, avoiding storing your credentials in the app.

Server Developers

Suragch has written an excellent tutorial on How to send yourself email notifications from a Dart server.


If you have created a tutorial yourself (or know of one) please open an issue, so it can be added to this list. Note that tutorials don't need to be in English!

Logging

The library uses the logging package. By default, no logs are output. To see the SMTP communication (which is helpful for debugging), configure a logger listener:

import 'package:logging/logging.dart';

void main() {
  Logger.root.level = Level.ALL; // defaults to Level.INFO
  Logger.root.onRecord.listen((LogRecord rec) {
    print('${rec.level.name}: ${rec.time}: ${rec.message}');
  });

  // ... rest of your code
}

Security Note: Credentials (passwords, tokens) in AUTH commands are masked (*******) in the logs to prevent accidental leakage.

FAQ

Q: How do I handle large attachments? A: mailer supports RFC 3030 (CHUNKING). If the server supports it, mailer will automatically stream the data using BDAT commands, which is more efficient than the standard DATA command.

Q: How do I use Gmail with 2FA? A: You must generate an App Password in your Google Account settings and use that instead of your standard password.

License

MIT

카테고리

의존성

의존성 목록 9 개

소스 저장소

이 패키지를 사용하는 프로젝트

순위